public bool IsNextShipColliding( List <List <BattleshipGridCell> > grid, BattleShip ship, GridCoordinate firstCell) { try { return(IsGuessCollidingWithBorders(grid, ship, firstCell) || IsGuessCollidingWithShips(grid, ship, firstCell)); } catch (ArgumentOutOfRangeException) { return(true); } }
public IShip FindShipAtCoordinate(GridCoordinate coordinate) { /* Go through all the ships */ foreach (KeyValuePair <ShipKind, IShip> aShip in this.shipList) { /* Look if a ship is positioned at a specific coordinate */ if (aShip.Value.CanBeFoundAtCoordinate(coordinate) == true) { /* ship found, return ship object */ return(aShip.Value); } } /* no ship found */ return(null); }
/// <summary> /// Marks the designated coordinate as walkable or unwalkable depending on the value of /// <paramref name="isWalkable"/>. /// </summary> /// <param name="lowerLeft"> The lower left of the area which should be marked as /// walkable/unwalkable. </param> /// <param name="size"> The size of the area that should be marked walkable or unwalkable. </param> /// <param name="isWalkable"> True if the position should be walkable, false otherwise. </param> public static void MarkWalkable(GridCoordinate lowerLeft, Size size, bool isWalkable) { if (AstarPath.active == null) { Debug.LogError("A* graph is null."); return; } AstarPath.active.UpdateGraphs(new GraphUpdateObject { bounds = CalculateBounds(lowerLeft, size), modifyWalkability = true, setWalkability = isWalkable, }); }
public GridCoordinate GetGridForModule(Entity entity) { for (var x = 0; x < Width; x++) { for (var y = 0; y < Height; y++) { var gridCoordinate = new GridCoordinate(x, y); if (GetModule(gridCoordinate) == entity) { return(gridCoordinate); } } } return(null); }
public void UpdateCellValue(string column, int row, int sheet, string value, string sheetId) { var reqs = new BatchUpdateSpreadsheetRequest(); reqs.Requests = new List <Request>(); string[] colNames = new[] { value }; // Create starting coordinate where data would be written to GridCoordinate gc = new GridCoordinate(); gc.ColumnIndex = GetNumberFromChar(column[0]); gc.RowIndex = row - 1; gc.SheetId = sheet; // Your specific sheet ID here Request rq = new Request(); rq.UpdateCells = new UpdateCellsRequest(); rq.UpdateCells.Start = gc; rq.UpdateCells.Fields = "*"; // needed by API, throws error if null // Assigning data to cells RowData rd = new RowData(); List <CellData> lcd = new List <CellData>(); foreach (String s in colNames) { ExtendedValue ev = new ExtendedValue(); ev.StringValue = s; CellData cd = new CellData(); cd.UserEnteredValue = ev; lcd.Add(cd); } rd.Values = lcd; // Put cell data into a row List <RowData> lrd = new List <RowData>(); lrd.Add(rd); rq.UpdateCells.Rows = lrd; // It's a batch request so you can create more than one request and send them all in one batch. Just use reqs.Requests.Add() to add additional requests for the same spreadsheet reqs.Requests.Add(rq); // Execute request BatchUpdateSpreadsheetResponse response = service.Spreadsheets.BatchUpdate(reqs, sheetId).Execute(); // Replace Spreadsheet.SpreadsheetId with your recently created spreadsheet ID }
public ShotResult ShootAtOpponent(Guid shooterPlayerId, GridCoordinate coordinate) { /* Check if the game is started */ if (this.IsStarted == true) { /* Get the player */ IPlayer player = GetPlayerById(shooterPlayerId); if (player == null) { /* No bombs loaded */ return(ShotResult.CreateMisfire("Player unknown")); } if (player.HasBombsLoaded == false) { /* No bombs loaded */ return(ShotResult.CreateMisfire("No bombs loaded")); } /* Get opponent */ IPlayer opponent = GetOpponent(player); /* Shoot at the opponent */ ShotResult result = player.ShootAt(opponent, coordinate); /* Reload bombs of opponent */ opponent.ReloadBombs(); /* Check if opponent is computer */ if (opponent is ComputerPlayer) { /* Upcast IPlayer to ComputerPlayer */ ComputerPlayer computer = (ComputerPlayer)opponent; /* Let the computer */ computer.ShootAutomatically(player); /* Reload bombs of player in case of computer */ player.ReloadBombs(); } return(result); } else { return(ShotResult.CreateMisfire("game not started")); } }
void RemoveShipCell() { Vector3 currentMousePosition = ReturnCurrentMousePosition(); GridCoordinate gridCoord = ReturnCellGridCoordinate(currentMousePosition); if (IsValidGridCell(gridCoord)) { int gridElement = CoordToElement(gridCoord); GridCell localGridCell = GridCells[gridElement]; if (localGridCell.hasShipCell == true) { localGridCell.hasShipCell = false; List <GridCoordinate> neighborCoords = new List <GridCoordinate>(localGridCell.shipCellComponent.neighborShipCells.Keys); for (int i = 0; i < neighborCoords.Count; i++) { int neighborElement = CoordToElement(neighborCoords[i]); GridCell neighborCell = GridCells[neighborElement]; ShipCell neighborShipCell = neighborCell.shipCellComponent; Vector2 neighborCheck = localGridCell.gridCoordinate.SumCoordinatesAsVector2(neighborCell.gridCoordinate); for (int j = 0; j < 6; j++) { if (neighborDirection[j] == neighborCheck) { neighborShipCell.hasCellNeighborAt.Remove(j); neighborShipCell.UpdateHullSection(j); } } neighborShipCell.neighborShipCells.Remove(localGridCell.gridCoordinate); } if (localGridCell.shipCellComponent.hasCellUpgrade) { RemoveCustomization(localGridCell.shipCellComponent); } Destroy(localGridCell.shipCell); localGridCell.shipCell = default(GameObject); localGridCell.shipCellComponent = default(ShipCell); } } }
public static bool AddEntityToEntity([NotNull] Entity entityToAdd, [NotNull] GridCoordinate locationToAddIt, [NotNull] Entity entityToAddItTo) { var physicalState = entityToAdd.GetState <PhysicalState>(); physicalState.ParentEntity = entityToAddItTo; physicalState.BottomLeftCoordinate = locationToAddIt; var targetEntityPhysicalState = entityToAddItTo.GetState <PhysicalState>(); var entitiesAtTargetLocation = targetEntityPhysicalState.GetEntitiesAtGrid(locationToAddIt).ToList(); if (!entitiesAtTargetLocation.Any() || entitiesAtTargetLocation.All(entity => !entity.GetState <PhysicalState>().IsTangible)) { targetEntityPhysicalState.ChildEntities.Add(entityToAdd); UpdateLocationLookup(entityToAdd, locationToAddIt, targetEntityPhysicalState); return(true); } return(false); }
public void DetermineTargetCoordinate_ShouldOnlyPickCoordinatesThatAreNotHitByABomb() { //Arrange _gridBuilder.WithAllSquaresWithStatus(GridSquareStatus.Miss); //Set some squares to Hit for (int i = 0; i < 10; i++) { var coordinate = new GridCoordinateBuilder(_grid.Size).Build(); _gridBuilder.WithSquareStatus(coordinate, GridSquareStatus.Hit); } //Set some squares to Untouched var untouchedCoordinates = new List <GridCoordinate>(); for (int i = 0; i < RandomGenerator.Next(2, _grid.Size + 1); i++) { int column = RandomGenerator.Next(0, _grid.Size - 1); var coordinate1 = new GridCoordinate(i, column); untouchedCoordinates.Add(coordinate1); _gridBuilder.WithSquareStatus(coordinate1, GridSquareStatus.Untouched); var coordinate2 = new GridCoordinate(i, column + 1); untouchedCoordinates.Add(coordinate2); _gridBuilder.WithSquareStatus(coordinate2, GridSquareStatus.Untouched); } //Act var determinedCoordinates = new List <GridCoordinate>(); int numberOfDeterminations = untouchedCoordinates.Count / 2; for (int i = 0; i < numberOfDeterminations; i++) { var coordinate = _strategy.DetermineTargetCoordinate(); determinedCoordinates.Add(coordinate); _gridBuilder.WithSquareStatus(coordinate, GridSquareStatus.Miss); } //Assert string invalidDeterminationMessage = $"When a grid has only {untouchedCoordinates.Count} untouched squares " + $"and DetermineTargetCoordinate is called {numberOfDeterminations} times, " + $"then {numberOfDeterminations} of the untouched squares should have been picked " + "(this test marks a square as Missed after it is picked)."; Assert.That(determinedCoordinates.All(c => untouchedCoordinates.Contains(c)), Is.True, invalidDeterminationMessage); }
public IGridInfo CreateFromGrid(IGrid grid) { GridInfo gridInfo = new GridInfo(); gridInfo.Size = grid.Size; gridInfo.Squares = new GridSquareInfo[gridInfo.Size][]; for (int row = 0; row < gridInfo.Size; row++) { gridInfo.Squares[row] = new GridSquareInfo[gridInfo.Size]; for (int col = 0; col < gridInfo.Size; col++) { GridCoordinate c = new GridCoordinate(row, col); gridInfo.Squares[row][col] = new GridSquareInfo(grid.Squares[c.Row, c.Column]); /* not clear what the bug is */ } } return(gridInfo); }
/// <summary> Calculates the bounds for a GraphUpdateObject. </summary> /// <param name="lowerLeft"> The lower left of the area which should be changed. </param> /// <param name="size"> The size of the area that should be changed. </param> /// <returns> The calculated bounds. </returns> private static Bounds CalculateBounds(GridCoordinate lowerLeft, Size size) { const float offset = 0.1f; // calculate the lower left and upper left, but bring in both sides by .1f; this is so that we // won't accidentally include grid nodes next to us that might be accidentally included due to // rounding errors. var lowerLeftVector = new Vector3(lowerLeft.X + offset, lowerLeft.Z + offset); var upperRightVector = new Vector3(lowerLeft.X + size.Width - offset, lowerLeft.Z + size.Height - offset); var vectorCenter = (lowerLeftVector + upperRightVector) / 2.0f; var vectorSize = upperRightVector - lowerLeftVector; var bounds = new Bounds(vectorCenter, vectorSize); return(bounds); }
public List <Entity> GetContainedModules() { var results = new List <Entity>(); for (var x = 0; x < Width; x++) { for (var y = 0; y < Height; y++) { var gridCoordinate = new GridCoordinate(x, y); if (GridIsFull(gridCoordinate)) { results.Add(GetModule(gridCoordinate)); } } } return(results); }
public void ShootAtOpponent_ShouldNotCatchApplicationExceptions() { //Arrange Guid userId = Guid.NewGuid(); Guid gameId = Guid.NewGuid(); GridCoordinate targetCoordinate = new GridCoordinate(1, 1); var existingGameMock = new Mock <IGame>(); IGame existingGame = existingGameMock.Object; _gameRepositoryMock.Setup(repo => repo.GetById(It.IsAny <Guid>())).Returns(existingGame); existingGameMock.Setup(game => game.ShootAtOpponent(It.IsAny <Guid>(), It.IsAny <GridCoordinate>())).Throws <ApplicationException>(); //Act + Assert Assert.That(() => _service.ShootAtOpponent(gameId, userId, targetCoordinate), Throws.InstanceOf <ApplicationException>()); }
private bool isPossibleShip(GridCoordinate coordinate) { int numberUntouched = 0; foreach (Direction direction in this.possibleDirections) { int numberUntouchedDirection = 1; GridCoordinate nextCoordinate = coordinate.GetNeighbor(direction); while (!nextCoordinate.IsOutOfBounds(this.opponentGrid.Size)) { if (opponentGrid.GetSquareAt(nextCoordinate).Status == GridSquareStatus.Untouched) { numberUntouchedDirection++; nextCoordinate = nextCoordinate.GetNeighbor(direction); } else { break; } } nextCoordinate = coordinate.GetNeighbor(direction.Opposite); while (!nextCoordinate.IsOutOfBounds(this.opponentGrid.Size)) { if (opponentGrid.GetSquareAt(nextCoordinate).Status == GridSquareStatus.Untouched) { numberUntouchedDirection++; nextCoordinate = nextCoordinate.GetNeighbor(direction.Opposite); } else { break; } } if (numberUntouchedDirection > numberUntouched) { numberUntouched = numberUntouchedDirection; } } if (numberUntouched < this.GetSmallestShipSize()) { return(false); } return(true); }
private void SingleClick(int button, GridCoordinate currentlySelectedGrid) { if (button == 0) { entitySystem.CreateEntity( StaticStates.Get <EntityLibraryState>().GetSelectedEntity(), StaticStates.Get <ActiveEntityState>().ActiveEntity, currentlySelectedGrid); } if (button == 1) { var selectedGrid = StaticStates.Get <SelectedState>().Grid; var activeEntity = StaticStates.Get <ActiveEntityState>().ActiveEntity; var selectedEntities = activeEntity.GetState <PhysicalState>().GetEntitiesAtGrid(selectedGrid).ToList(); selectedEntities.ForEach(entitySystem.RemoveEntity); } }
private IEnumerator ClickEvent(int button, GridCoordinate selectedGrid) { yield return(new WaitForEndOfFrame()); var count = 0f; while (count < GlobalConstants.DoubleClickTimeLimit) { if (Input.GetMouseButtonDown(button)) { DoubleClick(button); yield break; } count += Time.deltaTime; yield return(null); } SingleClick(button, selectedGrid); }
private bool IsGuessCollidingWithShips( List <List <BattleshipGridCell> > grid, BattleShip ship, GridCoordinate firstCell) { for (int i = 0; i < ship.Length; ++i) { var nextLine = ship.IsVertical ? firstCell.Line + i : firstCell.Line; var nextColumn = ship.IsVertical ? firstCell.Column : firstCell.Column + i; if (grid[nextLine][nextColumn] != BattleshipGridCell.Empty) { return(true); } } return(false); }
public IEnumerator NegativeOutOfGridRangeIndex() { yield return(null); var winDetector = GetWinDetector(); var move = new MoveData(); var coordinate = new GridCoordinate(0, 0); move.SetupFirstMoveToGrid(coordinate, BoardCellColor.Blue); winDetector.DoMove(move); coordinate.SetColumn(1); move.SetupFirstMoveToGrid(coordinate, BoardCellColor.White); winDetector.DoMove(move); coordinate.SetColumn(7); move.SetupFirstMoveToGrid(coordinate, BoardCellColor.Blue); Assert.That(() => winDetector.DoMove(move), Throws.TypeOf <Exception>()); }
public void Test_RobotPositionWebAPI_EndPoint1_Grid() { IGridCoordinate gridCoordinate = new GridCoordinate { MaxXCoordinate = 5, MaxYCoordinate = 3 }; string endPointURI = (new Uri(baseUri, "grid")).ToString(); using (var client = new HttpClient()) { var response = client.PostAsync(endPointURI, GetStringContent(gridCoordinate)).Result; Assert.IsTrue(response.IsSuccessStatusCode); if (response.IsSuccessStatusCode) { IGridIdentifer gridId = JsonConvert.DeserializeObject <GridIdentifer>(response.Content.ReadAsStringAsync().Result); Assert.AreEqual(1, gridId.GridID); } } }
public void Build_ShouldReturnMissMark_WhenShotMissed() { // arrange var prev = BattleshipGameState.Empty(gridSize); var guess = "B2"; var coord = new GridCoordinate(1, 1); _guessService.GetCordinates(guess).Returns(coord); var expected = BattleshipGameState.Empty(gridSize); expected.Grid[1][1] = BattleshipGridCell.Miss; // act var result = _servceUnderTest.Build(prev, guess); // assert Assert.AreEqual(expected.Grid, result.Grid); }
/// <summary> /// Get the direction when you go from coordinate 1 to coordinate 2 /// </summary> public static Direction FromCoordinates(GridCoordinate coordinate1, GridCoordinate coordinate2) { int xStep = coordinate2.Column - coordinate1.Column; if (xStep != 0) { xStep = xStep / Math.Abs(xStep); } int yStep = coordinate2.Row - coordinate1.Row; if (yStep != 0) { yStep = yStep / Math.Abs(yStep); } return(new Direction(xStep, yStep)); }
public static void UpdateCells(SheetsService service, String spreadsheetId, int gid, int row, int col, String[] value) { List <Request> requests = new List <Request>(); List <RowData> rowDatas = new List <RowData>(); for (int i = 0; i < value.Length; i++) { List <CellData> valuess = new List <CellData>(); ExtendedValue extendedValue = new ExtendedValue(); extendedValue.StringValue = value[i]; CellData cd = new CellData(); cd.UserEnteredValue = extendedValue; valuess.Add(cd); RowData rowData = new RowData(); rowData.Values = valuess; rowDatas.Add(rowData); } GridCoordinate gridCoordinate = new GridCoordinate(); gridCoordinate.SheetId = gid; gridCoordinate.RowIndex = row; gridCoordinate.ColumnIndex = col; UpdateCellsRequest updateCellsRequest = new UpdateCellsRequest(); updateCellsRequest.Rows = rowDatas; updateCellsRequest.Start = gridCoordinate; updateCellsRequest.Fields = "userEnteredValue"; Request request = new Request(); request.UpdateCells = updateCellsRequest; requests.Add(request); BatchUpdateSpreadsheetRequest batchUpdateRequest = new BatchUpdateSpreadsheetRequest(); batchUpdateRequest.Requests = requests; service.Spreadsheets.BatchUpdate(batchUpdateRequest, spreadsheetId).Execute(); }
/// <summary> Sets an area to have the cell values given by <paramref name="cellData"/>. </summary> /// <param name="bottomLeft"> The bottom left position of the area. </param> /// <param name="size"> The size of the area to set the value of. </param> /// <param name="cellData"> The value that the area should be set to. </param> public void Set(GridCoordinate bottomLeft, Size size, CellData cellData) { // TODO check for error conditions int width = size.Width; int height = size.Height; int startX = bottomLeft.X; int startZ = bottomLeft.Z; for (int x = startX; x < startX + width; x++) { for (int z = startZ; z < startZ + height; z++) { _gridChunk[new GridCoordinate(x, z)] = cellData; } } GridUpdate.MarkCost(bottomLeft, size, cellData.RawType * 10); }
public void Build_ShouldReturnBoardWithSingleShip_WhenSingleShipInConfiguration(int x, int y) { // arrange _config.Ships.Returns(new List <int> { 1 }); var coord = new GridCoordinate(x, y); _randomService.NextCell().Returns(coord); var expected = BattleshipGameState.Empty(gridSize).Grid; expected[x][y] = BattleshipGridCell.Ship; // act var result = _servceUnderTest.Build(); // assert Assert.AreEqual(expected, result.Grid); }
private Entity GetNeigbouringEntity(GridCoordinate grid, Direction direction) { switch (direction) { case Direction.Up: var up = GetGridInDirection(grid, Direction.Up); if (GridIsInModule(up) && GridIsFull(up)) { return(GetModule(up)); } return(null); case Direction.Down: var down = GetGridInDirection(grid, Direction.Down); if (GridIsInModule(down) && GridIsFull(down)) { return(GetModule(down)); } return(null); case Direction.Left: var left = GetGridInDirection(grid, Direction.Left); if (GridIsInModule(left) && GridIsFull(left)) { return(GetModule(left)); } return(null); case Direction.Right: var right = GetGridInDirection(grid, Direction.Right); if (GridIsInModule(right) && GridIsFull(right)) { return(GetModule(right)); } return(null); case Direction.None: return(null); default: throw new ArgumentOutOfRangeException("direction", direction, null); } }
public void CreateRandom_ShouldBeRandom() { int gridSize = 1000; bool isRandom = false; GridCoordinate previousCoordinate = GridCoordinate.CreateRandom(gridSize); int numberOfTries = 0; while (numberOfTries <= 15 && !isRandom) { GridCoordinate newCoordinate = GridCoordinate.CreateRandom(gridSize); if (newCoordinate != previousCoordinate) { isRandom = true; } previousCoordinate = newCoordinate; } Assert.That(isRandom, Is.True); }
private List <GridCoordinate> GetNeighbours(GridCoordinate coordinate, Direction[] possibleDirections, GridSquareStatus withStatus) { List <GridCoordinate> result = new List <GridCoordinate>(); foreach (Direction direction in possibleDirections) { GridCoordinate otherCoordinate = coordinate.GetNeighbor(direction); if (!otherCoordinate.IsOutOfBounds(this.opponentGrid.Size)) { IGridSquare otherSquare = this.opponentGrid.GetSquareAt(otherCoordinate); if (otherSquare.Status == withStatus) { result.Add(otherCoordinate); } } } return(result); }
public void DetermineTargetCoordinate_ShouldDetectTheShipWith2HitsWhenANeighborShipAlsoHasAHit() { for (int numberOfChecks = 0; numberOfChecks < 10; numberOfChecks++) { //Arrange GridCoordinate hit1 = new GridCoordinate(RandomGenerator.Next(2, _grid.Size - 2), RandomGenerator.Next(2, _grid.Size - 2)); GridCoordinate miss1 = new GridCoordinate(hit1.Row - 1, hit1.Column); GridCoordinate hit2 = new GridCoordinate(hit1.Row + 1, hit1.Column); GridCoordinate miss2 = new GridCoordinate(hit2.Row + 1, hit2.Column); GridCoordinate hit3 = new GridCoordinate(hit2.Row, hit2.Column + 1); var ship1 = new ShipBuilder(ShipKind.Carrier).Build(); var ship2 = new ShipBuilder(ShipKind.Battleship).Build(); _gridBuilder.WithSquareStatus(miss1, GridSquareStatus.Miss); _gridBuilder.WithSquareStatus(hit1, GridSquareStatus.Hit); _strategy.RegisterShotResult(hit1, ShotResult.CreateHit(ship1, true)); _gridBuilder.WithSquareStatus(hit2, GridSquareStatus.Hit); _strategy.RegisterShotResult(hit2, ShotResult.CreateHit(ship2, true)); _gridBuilder.WithSquareStatus(miss2, GridSquareStatus.Miss); _gridBuilder.WithSquareStatus(hit3, GridSquareStatus.Hit); _strategy.RegisterShotResult(hit3, ShotResult.CreateHit(ship2, true)); IList <GridCoordinate> expectedCoordinates = new List <GridCoordinate> { new GridCoordinate(hit3.Row, hit3.Column + 1), new GridCoordinate(hit2.Row, hit2.Column - 1) }; //Act GridCoordinate result = _strategy.DetermineTargetCoordinate(); Assert.That(expectedCoordinates.Contains(result), Is.True, $"Bij een grid met volgende situatie: missers -> {miss1} en {miss2}, rake schoten -> {hit1}, {hit2} en {hit3} " + $"moet er geschoten worden op ייn van de volgende coordinaten: {expectedCoordinates.ToArray().Print()}. " + $"De strategie kiest soms echter {result}"); Setup(); } }
public Entity CreateEntity(List <IState> states, Entity entityToAddItTo, GridCoordinate locationToAddIt) { var newStates = states.DeepClone(); var entity = BuildEntity(newStates); InitEnvironmentEntities(entity); if (entityToAddItTo != null && PhysicalState.AddEntityToEntity(entity, locationToAddIt, entityToAddItTo)) { EntityAdded(entity); return(entity); } if (entityToAddItTo == null) { EntityAdded(entity); return(entity); } return(null); }
/// <summary> /// Initializes a new instance of the <see cref="GribBox"/> class. /// </summary> /// <param name="msgHandle">The MSG handle.</param> /// <param name="nw">The nw.</param> /// <param name="se">The se.</param> public GribBox(GribHandle msgHandle, GridCoordinate nw, GridCoordinate se) { int err; var box = GribApiProxy.GribBoxNew(msgHandle, out err); if (err != 0) { throw GribApiException.Create(err); } var pts = GribApiProxy.GribBoxGetPoints(box, nw.Latitude, nw.Longitude, se.Latitude, se.Longitude, out err); if (err != 0) { throw GribApiException.Create(err); } _points = new GribPoints(SWIGTYPE_p_grib_points.getCPtr(pts).Handle, false); }