/// <summary> /// Asserts state expectations against a ship model. /// </summary> /// <param name="ship">The actual ship.</param> /// <param name="isSunk">The expected sunk state flag.</param> /// <param name="orientation">The expected orientation.</param> /// <param name="segmentCount">The expected number of segments.</param> private static void AssertShip(Ship ship, bool isSunk, ShipOrientation orientation, int segmentCount) { ship.Should().NotBeNull(); ship.IsSunk.Should().Be(isSunk); ship.Orientation.Should().Be(orientation); ship.Segments.Should().HaveCount(segmentCount); }
private void GridAIDrag(object sender, DragEventArgs e) { ShipButton shipButton = (ShipButton)e.Data.GetData(DataFormats.Serializable); int shipSize = shipButton.ShipSize; Point relativePoint = gridAI.PointToClient(new Point(e.X, e.Y)); Coordinates coordinates = gridAI.GetCoordinatesFromMouse(relativePoint.X, relativePoint.Y); ShipOrientation orientation = shiftKey_Down(e.KeyState) ? ShipOrientation.Horizontal : ShipOrientation.Vertical; int modX = orientation == ShipOrientation.Horizontal ? 1 : 0; int modY = orientation == ShipOrientation.Vertical ? 1 : 0; if (gridAI.CurrentHover == null) { gridAI.CurrentHover = new FieldHover(); gridAI.CurrentHover.HoverSize = shipSize; gridAI.CurrentHover.ShipPiece = shipButton.ShipPiece; } gridAI.CurrentHover.MouseX = relativePoint.X; gridAI.CurrentHover.MouseY = relativePoint.Y; gridAI.CurrentHover.Orientation = orientation; gridAI.CurrentHover.Coordinates = coordinates; if (ShipCanFit(coordinates, shipSize, modX, modY)) { e.Effect = DragDropEffects.Copy; gridAI.CurrentHover.HoverSize = shipSize; } else { e.Effect = DragDropEffects.None; gridAI.CurrentHover.HoverSize = 0; } gridAI.Invalidate(); }
private void Validate(Ship ship, ShipOrientation orientation, Board board, int row, int column) { var errorMessage = "Ship's placement position is out of bounds"; if (row > board.Rows) { throw new IndexOutOfRangeException(errorMessage); } if (column > board.Columns) { throw new IndexOutOfRangeException(errorMessage); } if (orientation == ShipOrientation.Horizontal) { if (column + ship.Size > board.Columns) { throw new IndexOutOfRangeException(errorMessage); } } else { if (row + ship.Size > board.Rows) { throw new IndexOutOfRangeException(errorMessage); } } }
//Voir si ça va écraser un bateau private bool CheckIfStomping(Ships ship, ShipOrientation orientation, int rowStart, int colStart) { bool Stomping = false; if (orientation == ShipOrientation.Vertical) { for (int i = rowStart; i < rowStart + ship.GetLength() && !Stomping; i++) { string val = DGV_Demo.Rows[i].Cells[colStart].Value.ToString(); if (val != "" && val != ship.GetCode()) { Stomping = true; } } } else if (orientation == ShipOrientation.Horizontal) { for (int i = colStart; i < colStart + ship.GetLength() && !Stomping; i++) { string val = DGV_Demo.Rows[rowStart].Cells[i].Value.ToString(); if (val != "" && val != ship.GetCode()) { Stomping = true; } } } return(Stomping); }
/// <summary> /// Добавляет корабль на карту /// </summary> /// <param name="x">Координата X</param> /// <param name="y">Координата Y</param> /// <param name="countDeck">Количество палуб</param> /// <param name="orientation">Ориентация корабля</param> public void CreateShip(int x, int y, int countDeck, ShipOrientation orientation) { DTOShip ship = new DTOShip(); ship.DeckCount = countDeck; ship.Orientation = orientation; ship.Coordinates = new XYCoordinate() { X = x, Y = y }; Ships.Add(ship); int startPositionX = x; int startPositionY = y; for (int i = 0; i < countDeck; i++) { if (orientation == ShipOrientation.Horisontal) { var field = Map[startPositionY, startPositionX]; field.State = FieldState.Ship; field.Ship = ship; startPositionX++; } else { var field = Map[startPositionY, startPositionX]; field.State = FieldState.Ship; field.Ship = ship; startPositionY++; } } }
private bool canPlaceShip(Ship ship, int row, int col, GridSpace[,] board, ShipOrientation orientation) { int targetRow = row; int targetCol = col; int size = ship.size; while (size != 0) { if (targetRow >= board.GetLength(0) || targetRow < 0) { return(false); } if (targetCol >= board.GetLength(1) || targetCol < 0) { return(false); } if (board[targetRow, targetCol].ship != null) { return(false); } if (orientation == ShipOrientation.HORIZONTAL) { targetCol++; } else { targetRow++; } size--; } return(true); }
public IActionResult AddBattleshipsOnBoard([Required, Range(1, 10)] int shipLength, [Required] ShipOrientation shipOrientation, [Required, Range(1, 10)] int shipStartRow, [Required, Range(1, 10)] int shipStartColumn) { try { var game = _gameService.GetGame(); if (game?.Player.Board == null) { throw new Exception("Invalid Board"); } var ship = _playerService.PlaceShip(shipLength, shipOrientation, new Coordinate(shipStartRow, shipStartColumn)); return(ship != null ? Ok(ship) : StatusCode(StatusCodes.Status500InternalServerError, "Ship could not be placed")); } catch (IndexOutOfRangeException) { return(BadRequest("Ship coordinates fall outside board boundary")); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex)); } }
/// <summary> /// Places the dragged ship onto the grid /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GridAIDragDrop(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; ShipButton shipButton = (ShipButton)e.Data.GetData(DataFormats.Serializable); Ship selectedShip = SelectShip(shipButton.ShipSize); Point relativePoint = gridAI.PointToClient(new Point(e.X, e.Y)); int shipSize = selectedShip.Length; Coordinates coordinates = gridAI.GetCoordinatesFromMouse(relativePoint.X, relativePoint.Y); ShipOrientation direction = shiftKey_Down(e.KeyState) ? ShipOrientation.Horizontal : ShipOrientation.Vertical; int modX = direction == ShipOrientation.Horizontal ? 1 : 0; int modY = direction == ShipOrientation.Vertical ? 1 : 0; int count = 0; for (int x = coordinates.X; x <= coordinates.X + ((shipSize - 1) * modX); x++) { for (int y = coordinates.Y; y <= coordinates.Y + ((shipSize - 1) * modY); y++) { Coordinates coords = new Coordinates(x, y); gridAI.SetCellShip(coords, shipButton.ShipPiece, count++, direction); } } selectedShip.Place(coordinates, direction); shipButton.Visible = false; gridAI.CurrentHover = null; gridAI.Invalidate(); AttemptPlayMatch(); }
/// <summary> /// Конструктор /// </summary> /// <param name="parSize">Длина корабля</param> /// <param name="parOrientation">Ориентация корабля</param> /// <param name="parPosition">Позиция начальной точки корабля</param> /// <param name="parPlayerType">Тип игрока, владеющего кораблём</param> public Ship(int parSize, ShipOrientation parOrientation, Point parPosition, PlayerTypes parPlayerType = PlayerTypes.User) { _size = parSize; _orientation = parOrientation; _playerType = parPlayerType; AddPosition(parPosition); }
/// <summary> ///Setup postion of ship /// </summary> private Point[] SetPosition(Point Startingpoint, ShipOrientation Orientation, int Length) { Point[] points = new Point[Length]; for (int i = 0; i < Length; i++) { points[i] = new Point(Startingpoint.X, Startingpoint.Y); if (Orientation == ShipOrientation.Horizontal) { Startingpoint.Y++; int Y = Startingpoint.Y; if (Startingpoint.X == 0) { int X = Startingpoint.X; } } else if (Orientation == ShipOrientation.Vertical) { Startingpoint.X++; int X = Startingpoint.X; if (Startingpoint.Y == 0) { int Y = Startingpoint.Y; } } } return(points); }
/// <summary> /// Изменение ориентации корабля. /// </summary> /// <param name="parShipOrientation">Ориентация корабля</param> /// <returns></returns> public ShipOrientation ChangeShipOrientation(ShipOrientation parShipOrientation) { if (parShipOrientation == ShipOrientation.Horizontal) { return(ShipOrientation.Vertical); } return(ShipOrientation.Horizontal); }
public void AddingShipOutsideBoardBoundaryThrowsException(int length, ShipOrientation orientation, int row, int column) { AddShipToBoard(length, orientation, row, column); var badRequestObjectResult = Result.Should().BeOfType <BadRequestObjectResult>().Subject; badRequestObjectResult.Value.Should().Be("Ship coordinates fall outside board boundary"); }
public ShipControlCommons(MyGridProgram program, UpdateType updateType, ShipOrientation shipOrientation, string shipGroup = null, ZAStorage storage = null) : base(program, updateType, shipGroup: shipGroup, storage: storage) { this.shipOrientation = shipOrientation; }
public Ship(int length, ShipOrientation orientation, int x, int y, int hitCount) { Length = length; Orientation = orientation; X = x; Y = y; HitCount = hitCount; }
public Ship(string name, int length, ShipOrientation so) { Name = name; Coords = new int[length, 2]; Length = length; Orientation = so; HitCount = 0; }
public NetworkSprite(MDI_Game.Sprite sprite, bool EnabelOverride) { ShipType = sprite.ShipType.ShipEnum; Location = sprite.Location; CoveredTiles = sprite.CoveredTileCords; ShipOrientation = sprite.ShipOrientation; Enabled = EnabelOverride; ShipDestroyed = sprite.ShipDestroyed; }
public void AddingShipToBoardReturnsAValidShipId(int length, ShipOrientation orientation, int row, int column) { AddShipToBoard(length, orientation, row, column); var okObjectResult = Result.Should().BeOfType <OkObjectResult>().Subject; var ship = okObjectResult.Value.Should().BeAssignableTo <Ship>().Subject; Assert.NotEmpty(ship.ShipId); Assert.Equal(length, ship.Coordinates.Count); Assert.Equal(length, ship.Length); Assert.Equal(0, ship.Hits); }
private Position GetPositionOffset(ShipOrientation shipOrientation) { var rowOffset = shipOrientation == ShipOrientation.Vertical ? 1 : 0; var columnOffset = shipOrientation == ShipOrientation.Horizontal ? 1 : 0; return(new Position(columnOffset, rowOffset)); }
private void ValidateGeneratiedCoordinatesForPlacingShip(Ship ship, ShipOrientation orientation, Coordinates coordinates) { if (!CheckIfItPossibleToPlaceAShipOnTheGrid(ship, orientation, coordinates)) { PlaceShipOnTheGrid(ship); } else { UpdateGrid(ship, orientation, coordinates); } }
public void ShouldReturnValidCoordinatesForShip(ShipType shipType, ShipOrientation orientation) { var ship = _shipFactory.MakeShip(shipType); var coordinates = _boardGenerator.GetStartingCoordinatesForShip(ship, orientation); Assert.IsInstanceOf <Coordinates>(coordinates); Assert.GreaterOrEqual(coordinates.X, 0); Assert.GreaterOrEqual(coordinates.Y, 0); Assert.LessOrEqual(coordinates.X, 10); Assert.LessOrEqual(coordinates.Y, 10); }
/// <summary> /// Adds a new ship to the board at the specified position. /// </summary> /// <param name="board">The board to update.</param> /// <param name="xIndex">The index on the X-axis.</param> /// <param name="yIndex">The index on the Y-axis.</param> /// <param name="orientation">The axis orientation of the ship on the board.</param> /// <param name="length">The number of segments to create.</param> /// <returns>True if the ship was added successfully, False if the ship could not be added.</returns> public bool AddShip(Board board, int xIndex, int yIndex, ShipOrientation orientation, int length) { if (length > board.Game.MaximumShipLength || length < board.Game.MinimumShipLength) { return(false); } var ship = new Ship { Orientation = orientation }; for (var i = 0; i < length; i++) { // check if position is currently outside board if (xIndex < 0 || xIndex > board.Width - 1 || yIndex < 0 || yIndex > board.Height - 1) { return(false); } // check if there is already a segment at this position var segment = FindSegmentAtPosition(board, xIndex, yIndex); if (segment != null) { return(false); } // add the segment at current position ship.Segments.Add(new ShipSegment { Ship = ship, XIndex = xIndex, YIndex = yIndex }); // increment position to next segment if needed if (i < length - 1) { switch (orientation) { case ShipOrientation.Horizontal: xIndex++; break; case ShipOrientation.Vertical: yIndex++; break; } } } // all segments created successfully so add ship to board board.Ships.Add(ship); return(true); }
public ShipControlCommons(MyGridProgram program, ShipOrientation shipOrientation, string shipGroup = null, ZAStorage storage = null) : base(program, shipGroup: shipGroup, storage: storage) { this.shipOrientation = shipOrientation; // Use own programmable block as reference point Reference = program.Me; ReferencePoint = Reference.GetPosition(); }
public void AddShip(ShipType type, Coordinate coordinate, ShipOrientation orientation) { Ship ship = new Ship(type); bool isHorizontal = orientation == ShipOrientation.Horizontal; int start = (isHorizontal ? coordinate.X : coordinate.Y); for (int i = start; i < start + (int)type; i++) { Square square = _squares[(isHorizontal ? coordinate.Y : i), (isHorizontal ? i : coordinate.X)]; square.AddShip(ship); } }
public Coordinates GetStartingCoordinatesForShip(Ship ship, ShipOrientation orientation) { int endIndex = GetEndIndexForShipRandom(ship, orientation); int firstCoordinate = _randFirstCoordinateOfShip.Next(1, endIndex); int endIndexForSecondCoordinate = orientation == ShipOrientation.Vertical ? _board.Columns - 1 : _board.Rows - 1; int secondCoordinate = _randSecondCoordinateOfShip.Next(1, endIndexForSecondCoordinate); int x = orientation == ShipOrientation.Vertical ? firstCoordinate : secondCoordinate; int y = orientation == ShipOrientation.Horizontal ? firstCoordinate : secondCoordinate; var coordinate = new ShipCoordinates(x, y); return(coordinate); }
// Member Data ----- END ---------------// /// --- Supporting Methods -- Private functions -------------------- START -------------- // private ShipModel GetShipModel(ShipType shipType, ShipOrientation orientation, int x = 1, int y = 1) { var shipModel = new ShipModel(); shipModel.Ship = shipType; shipModel.Orientation = orientation; shipModel.StartPoint = new ShipPointLocationModel() { XCoordinate = x, YCoordinate = y }; return(shipModel); }
private void UpdateGrid(Ship ship, ShipOrientation orientation, Coordinates coordinates) { for (int i = 0; i < ship.CoordinatesFields.Count(); i++) { int x = orientation == ShipOrientation.Vertical ? coordinates.X + i : coordinates.X; int y = orientation == ShipOrientation.Horizontal ? coordinates.Y + i : coordinates.Y; _board.Grid[x, y].IsOccupied = true; _board.Grid[x, y].ShipId = ship.Id; _board.Grid[x, y].Status = Status.Occupied; ship.CoordinatesFields[i] = new ShipCoordinates(x, y); } }
public Ship(List <Cell> ships, List <Cell> margin, ShipOrientation orientation) { _orientation = orientation; _isDead = false; _state = ShipState.Normal; if (ships == null) { throw new ArgumentNullException("cells"); } if (ships.Count == 0) { throw new ArgumentException("Список ячеек, занимаемых кораблем пуст."); } if (ships.Count < 1 || ships.Count > 4) { throw new ArgumentException("Количество палуб дожно быть в пределах от 1 до 4"); } foreach (Cell cell in ships) { cell.Type = CellType.Ship; } _palubs = ships; if (margin == null) { throw new ArgumentNullException("margin"); } if (margin.Count < 1) { throw new ArgumentException("Количество ячеек окружения должно быть больше 1-ой."); } foreach (Cell cell in margin) { cell.Type = CellType.Margin; } _margin = margin; if (ships.Count == 1) { _orientation = ShipOrientation.None; } else { if (_orientation == ShipOrientation.None) { throw new ArgumentException("Для кораблей с числом палуб больше 1-й необходимо задать ориентацию"); } _orientation = orientation; } }
private byte GetPossibleStartPositionInAxios(ShipOrientation shipOrientation, byte axiosSelected, byte boardSize, byte shipSize) { IList <byte> pointsInLine; if (shipOrientation == ShipOrientation.Horizontal) { pointsInLine = coordinatesWithShip.Where(p => p.X == axiosSelected).OrderBy(p => p.Y).Select(p => p.Y).ToList(); } else { pointsInLine = coordinatesWithShip.Where(p => p.Y == axiosSelected).OrderBy(p => p.X).Select(p => p.X).ToList(); } IList <byte> possibilities = new List <byte>(); for (byte i = 0; i <= boardSize - shipSize; i++) { if (!pointsInLine.Any()) { possibilities.Add(i); continue; } else { if (pointsInLine.First() >= shipSize || pointsInLine.Last() <= boardSize - 1 - shipSize) { possibilities.Add(i); continue; } else { byte prevValue = pointsInLine.First(); for (int j = 1; j < pointsInLine.Count; j++) { if (pointsInLine[j] >= prevValue + shipSize) { possibilities.Add(i); continue; } } } } } if (possibilities.Count == 1) { return(possibilities[0]); } return(possibilities[new Random().Next(possibilities.Count - 1)]); }
public void PlaceShip_WhenValidCoordinatesGiven_ReturnsShip(int x, int y, int length, ShipOrientation shipOrientation) { var board = new Board(); board.ActivateBoard(); var initialCoordinate = new Coordinate(x, y); var added = board.PlaceShip(initialCoordinate, length, shipOrientation); Assert.True(added); Assert.Equal(length, board.Ships[0].Coordinates.Count); }
public void PlaceShip_WhenNonValidCoordinatesGiven_ReturnsNull(int x, int y, int length, ShipOrientation shipOrientation) { var board = new Board(); board.ActivateBoard(); var initialCoordinate = new Coordinate(x, y); var added = board.PlaceShip(initialCoordinate, length, shipOrientation); Assert.False(added); Assert.Empty(board.Ships); }
public void SetCellShip(Coordinates coordinates, ShipPiece shipPiece, int section, ShipOrientation orientation) { Cell cell; if (!Cells.TryGetValue(coordinates, out cell)) { cell = new Cell(); cell.Coordinates = coordinates; Cells.Add(coordinates, cell); } cell.ShipPiece = shipPiece; cell.ShipSection = section; cell.Orientation = orientation; }
public Ship(ShipType shipType, ShipOrientation orientation, int gridWidth, int gridHeight) { Id = Guid.NewGuid(); ShipType = shipType; switch (shipType) { case ShipType.Destroyer: Length = 4; Health = 4; break; case ShipType.Battleship: Length = 5; Health = 5; break; } Orientation = orientation; Position = SetShipPosition(gridWidth, gridHeight); }
public System.Collections.IEnumerator PlaceShip(Ship ship) { bool placed = false; bool valid = false; if (ship != null) { ship.LoadModel(); ship.HideModel(); while (!placed) { yield return null; if (Input.GetKeyDown("r")) { if(placeOrientation == ShipOrientation.Horizontal) placeOrientation = ShipOrientation.Vertical; else placeOrientation = ShipOrientation.Horizontal; } if (Input.GetMouseButtonDown(0) && valid) { placed = true; break; } Point cast = getBoardRayCast(false, Color.white); if (ship.Place(cast, placeOrientation, gameSize)) { bool collides = false; foreach (Ship s in mShips) { if (s != ship) collides |= ship.ConflictsWith(s); } if (!collides) { ship.ShowModel(); valid = true; } else { ship.HideModel(); valid = false; } } else { ship.HideModel(); valid = false; } } } waitingForRoutine = false; curship++; }
private static Ship GetFourDeckShip(ShipOrientation orientation = ShipOrientation.Vertical) { return new Ship( ShipType.FourDeck, orientation, new Coordinate('a', 1)); }
private ShipOrientation RandomShipOrientation() { var orientations = new ShipOrientation[] { ShipOrientation.Horizontal, ShipOrientation.Vertical }; return orientations[rand.Next(2)]; }
public ShipMovedEvent(Ship ship, Coordinates position, ShipOrientation orientation) : base(ship) { Position = position; Orientation = orientation; }
public Ship(ShipType type, ShipOrientation orientation, Coordinate startingPoint) : this(type) { Orientation = orientation; StartingPoint = startingPoint; }
/// <summary> /// This method randomly returns one of two ShipOrientation enums. /// </summary> /// <returns>A randomly selected ShipOrientation.</returns> private ShipOrientation RandomShipOrientation() { //The controller first makes a two-element array that contains the two possible orientations. var orientations = new ShipOrientation[] { ShipOrientation.Horizontal, ShipOrientation.Vertical }; //Then the controller uses the random number generator "rand" to choose either a 0 or a 1 to //pick the index of a ShipOrientation randomly. The ShipOrientation is then returned back to the //caller. return orientations[rand.Next(2)]; }
//Voir si ça va écraser un bateau private bool CheckIfStomping(Ships ship, ShipOrientation orientation, int rowStart, int colStart) { bool Stomping = false; if (orientation == ShipOrientation.Vertical) { for (int i = rowStart; i < rowStart + ship.GetLength() && !Stomping; i++) { string val = DGV_Demo.Rows[i].Cells[colStart].Value.ToString(); if (val != "" && val != ship.GetCode()) { Stomping = true; } } } else if (orientation == ShipOrientation.Horizontal) { for (int i = colStart; i < colStart + ship.GetLength() && !Stomping; i++) { string val = DGV_Demo.Rows[rowStart].Cells[i].Value.ToString(); if (val != "" && val != ship.GetCode()) { Stomping = true; } } } return Stomping; }
/// <summary> /// Places this <see cref="Ship"/> with the <paramref name="location"/> and <paramref name="orientation"/>. /// Sets the state of being placed to true. /// </summary> /// <param name="location">The <see cref="Coordinates"/> of the bottom-most/left-most part of /// the <see cref="Ship"/>.</param> /// <param name="orientation">The <see cref="ShipOrientation"/> to set.</param> public void Place(Coordinates location, ShipOrientation orientation) { InvokeEvent(new ShipMovedEvent(this, location, orientation)); }
//Placer un bateau selon les données entrées private void PlaceShip(Ships ship, ShipOrientation orientation, int rowStart, int colStart) { ClearSeaFromShip(ship); if (orientation == ShipOrientation.Vertical) { for (int i = rowStart; i < rowStart + ship.GetLength(); i++) { DGV_Demo.Rows[i].Cells[colStart].Value = ship.GetCode(); } } else if (orientation == ShipOrientation.Horizontal) { for (int i = colStart; i < colStart + ship.GetLength(); i++) { DGV_Demo.Rows[rowStart].Cells[i].Value = ship.GetCode(); } } }
public void Place(Point location, ShipOrientation orientation) { this.location = location; this.orientation = orientation; this.isPlaced = true; }
public bool Place(Point location, ShipOrientation orientation, Size boardSize) { this.mLocation = location; this.mOrientation = orientation; this.isPlaced = true; if (!IsValid(boardSize)) { mLocation = new Point(-1, -1); isPlaced = false; return false; } return true; }