public void AddToGrid(Ship BS, int y, int x, int dir, int size) { if (dir == 0) { BS.SetPositions(y, x, dir); int c = x; for (int r = y; r < (y + size); r++) { board[r, c] = 1; } } else { BS.SetPositions(y, x, dir); for (int r = y; r == y; r++) { for (int c = x; c < x + size; c++) { board[r, c] = 1; } } } }
/// <summary> /// Initializes gameplay phase /// </summary> /// <param name="difficulty">The chosen difficulty</param> /// <param name="buttons">The submitted placement of ships</param> /// <param name="name">The name of the player</param> public PlayGame(Difficulty difficulty, Button[] buttons, string name, Ship[] ships, MainWindow main) { InitializeComponent(); this.main = main; // Set player name this.name = name.ToLower().Replace(' ', '_'); // Set player and computer's ships shipsPlayer = ships; shipsComputer = new Ship[] { new Ship(ShipName.AIRCRAFT_CARRIER, 5), new Ship(ShipName.BATTLESHIP, 4), new Ship(ShipName.SUBMARINE, 3), new Ship(ShipName.CRUISER, 3), new Ship(ShipName.DESTROYER, 2) }; // Set button field arrays buttonsPlayer = new Button[100]; PlayerShips.Children.CopyTo(buttonsPlayer, 0); buttonsComputer = new Button[100]; ComputerShips.Children.CopyTo(buttonsComputer, 0); common = new Common(ComputerShips, buttonsComputer); computerAI = new ComputerAI(this, difficulty); initializeGame(buttons); }
public void AddListToGrid(Ship[] BS) { int[] Loc; for (int i = 0; i < 5; i++) { do { Loc = GetOpenLoc(BS[i]); } while (Loc[0] == -1); AddToGrid(BS[i], Loc[0], Loc[1], Loc[2], BS[i].GetSize()); ships[i] = BS[i]; } }
public void TestIsOutOfBounds() { Ship[] ships = new Ship[] { shipA, shipB, shipC, shipD, shipE, shipF, shipD }; int[] outOfBoundsIndexes = new int[] { 4 }; for (int i = 0; i < ships.Length; i++) { bool isOutofBounds = false; foreach (var sec in ships[i].Sections) { if (sph.IsOutOfBounds(sec.Coord)) { isOutofBounds = true; break; } } if (outOfBoundsIndexes.Contains(i)) { Assert.IsTrue(isOutofBounds); } else { Assert.IsFalse(isOutofBounds); } } }
private void ShipClicked(object sender, System.Windows.Input.MouseButtonEventArgs e) { if(possiblePosition) { if(currentShip != null) { placedShips.Add(currentShip); currentShip = null; } currentShip = (Ship)sender; currentShip.PreviewMouseDown -= ShipClicked; currentShip = currentShip.Clone(); int length = currentShip.Size; currentShip.Width = Playfield.Width / (Playfield.nrOfRowsCols + 1) * length; currentShip.Height = Playfield.Width / (Playfield.nrOfRowsCols + 1); Grid.SetRow(currentShip, 1); Grid.SetColumn(currentShip, 1); Grid.SetColumnSpan(currentShip, length); Playfield.Fields.Children.Add(currentShip); checkOverlapping(); } this.Focus(); }
private bool IsPlacementConflict(Ship.Section a, Ship.Section b) { bool xIsOutsideLimit = (Math.Abs(a.Coord.X - b.Coord.X) >= minDistBetweenShips); bool yIsOutsideLimit = (Math.Abs(a.Coord.Y - b.Coord.Y) >= minDistBetweenShips); if (xIsOutsideLimit || yIsOutsideLimit) { return false; } else return true; }
public bool PlacementCreatesConflict(Ship s, List<Ship> placedShips) { return s.Sections.Any(secOnS => placedShips.Any(ps => ps.Sections.Any(secOnPS => IsPlacementConflict(secOnPS, secOnS)))); }
public bool IsInvalidPlacement(Ship s) { // Keep everything in bounds if (s.Sections.Any(section => IsOutOfBounds(section.Coord))) { return true; } // Determine a single orientation bool isVertical = s.Sections.All(section => section.Coord.X == s.Sections[0].Coord.X); bool isHorizontal = s.Sections.All(section => section.Coord.Y == s.Sections[0].Coord.Y); if (!(isVertical ^ isHorizontal)) { return true; } // Get a sorted list of the consecutive values along the orientation List<int> consecNums = new List<int>(); foreach (var section in s.Sections) { if (isVertical) { consecNums.Add(section.Coord.Y); } else { consecNums.Add(section.Coord.X); } } consecNums.Sort(); // Ensure these values are all adjacent to one another for (int i = 0; i < consecNums.Count - 1; i++) { if (consecNums[i + 1] != (consecNums[i] + 1)) { return true; } } // Good placement return false; }
protected virtual Ship PlaceShip(Ship s, List<Ship> placedShips) { Random r = new Random(); bool isSafePlacement = false; while (!isSafePlacement) { isSafePlacement = true; int x = r.Next(MaxCoords.X); int y = r.Next(MaxCoords.Y); int secMod = 0; int xMod = 0; int yMod = 0; #region Pick a random direction switch (r.Next(3)) { case 0: yMod = 1; // Up break; case 1: yMod = -1; // Down break; case 2: xMod = -1; // Left break; case 3: xMod = 1; // Right break; default: break; } #endregion // Place ship foreach (var sec in s.Sections) { sec.Coord = new Coordinate(x + (secMod * xMod), y + (secMod * yMod)); secMod++; } // Check for safe placement if (sph.IsInvalidPlacement(s) || sph.PlacementCreatesConflict(s, placedShips)) { isSafePlacement = false; } } return s; }
/// <summary> /// The computer's turn, where the computer will act according to the difficulty chosen /// </summary> public Button computerTurn() { Button chosen = null; // Legendary mode if (difficulty.Equals(Difficulty.Legendary)) { chosen = computerLegendary(); } else { // Last move was a hit if (computerMoves.Count != 0 && lastHitIndex > -1) { chosen = killerMode(); } // Go to default difficulty move if (chosen == null) { // Choose difficulty if (difficulty.Equals(Difficulty.Easy)) { chosen = computerEasy(); } if (difficulty.Equals(Difficulty.Medium)) { chosen = computerMedium(); } if (difficulty.Equals(Difficulty.Hard)) { chosen = computerHard(); } } } // If move was a hit if (chosen.Tag != null) { lastHitIndex = Array.IndexOf(playGame.buttonsPlayer, chosen); lastHitShip = (Ship)chosen.Tag; } return chosen; }
private bool PlaceShipOnBoard(Ship s) { if (sph.IsInvalidPlacement(s)) { return false; } // Setup image Image ship = new Image(); ship.Name = s.Name; ship.Source = new BitmapImage(GetImageForShip(s)); ship.HorizontalAlignment = HorizontalAlignment.Center; ship.VerticalAlignment = VerticalAlignment.Center; ship.Stretch = Stretch.UniformToFill; // Determine coords and span int maxX = s.Sections.Max(sec => sec.Coord.X); int minX = s.Sections.Min(sec => sec.Coord.X); int maxY = s.Sections.Max(sec => sec.Coord.Y); int minY = s.Sections.Min(sec => sec.Coord.Y); Grid.SetColumn(ship, minX); Grid.SetColumnSpan(ship, maxX - minX + 1); Grid.SetRow(ship, minY); Grid.SetRowSpan(ship, maxY - minY + 1); shipBoard.Children.Add(ship); placedShips.Add(ship); return true; }
public bool UpdateShip(Ship BS) { if (BS == null) return false; int[,] locs = BS.GetPositions(); for (int r = 0; r < BS.GetSize(); r++) { if (board[locs[r, 0], locs[r, 1]] == 1) { return false; } } return true; }
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.LayoutRoot = ((System.Windows.Controls.Grid)(target)); return; case 2: this.content = ((System.Windows.Controls.Grid)(target)); return; case 3: this.healthbar = ((System.Windows.Controls.Grid)(target)); return; case 4: this.CarrierTxt = ((System.Windows.Controls.Label)(target)); return; case 5: this.CarrierShip = ((BattleShip.Ship)(target)); return; case 6: this.CarrierHP = ((BattleShip.HealthBar)(target)); return; case 7: this.BattleshipTxt = ((System.Windows.Controls.Label)(target)); return; case 8: this.BattleshipShip = ((BattleShip.Ship)(target)); return; case 9: this.BattleshipHP = ((BattleShip.HealthBar)(target)); return; case 10: this.DestroyerTxt = ((System.Windows.Controls.Label)(target)); return; case 11: this.DestroyerShip = ((BattleShip.Ship)(target)); return; case 12: this.DestroyerHP = ((BattleShip.HealthBar)(target)); return; case 13: this.SubmarineTxt = ((System.Windows.Controls.Label)(target)); return; case 14: this.SubmarineShip = ((BattleShip.Ship)(target)); return; case 15: this.SubmarineHP = ((BattleShip.HealthBar)(target)); return; case 16: this.PatrolboatTxt = ((System.Windows.Controls.Label)(target)); return; case 17: this.PatrolboatShip = ((BattleShip.Ship)(target)); return; case 18: this.PatrolboatHP = ((BattleShip.HealthBar)(target)); return; case 19: this.playfield = ((BattleShip.Playfield)(target)); return; case 20: this.playerName = ((System.Windows.Controls.TextBlock)(target)); return; case 21: this.Disabled = ((System.Windows.Shapes.Rectangle)(target)); return; } this._contentLoaded = true; }
public void SetShip(Ship ship) { this.ship = ship; }
/// <summary> /// AddShip add a ship to the SeaGrid /// </summary> /// <param name="row">row coordinate</param> /// <param name="col">col coordinate</param> /// <param name="direction">direction of ship</param> /// <param name="newShip">the ship</param> private void AddShip(int row, int col, Direction direction, Ship newShip) { try { int size = newShip.Size; int currentRow = row; int currentCol = col; int dRow = 0; int dCol = 0; if (direction == Direction.LeftRight) { dRow = 0; dCol = 1; } else { dRow = 1; dCol = 0; } //place ship's tiles in array and into ship object int i = 0; for (i = 0; i <= size - 1; i++) { if (currentRow < 0 | currentRow >= Width | currentCol < 0 | currentCol >= Height) { throw new InvalidOperationException("Ship can't fit on the board"); } _GameTiles[currentRow, currentCol].Ship = newShip; currentCol += dCol; currentRow += dRow; } newShip.Deployed(direction, row, col); } catch (Exception e) { newShip.Remove(); //if fails remove the ship throw new ApplicationException(e.Message); } finally { if (Changed != null) { Changed(this, EventArgs.Empty); } } }
//this function creates sets the ships on the gameboard private static void SetGame(GameBoard gb) { Ship[] ships = new Ship[7]; ships[0] = new Ship(5); ships[1] = new Ship(4); ships[2] = new Ship(3); ships[3] = new Ship(2); ships[4] = new Ship(2); //new ships ships[5] = new Ship(1); ships[6] = new Ship(1); gb.AddListToGrid(ships); }
public void Initialize(Coordinate maxCoords, Ship[] startingShips) { this.Ships = startingShips; this.MaxCoords = maxCoords; this.Attacks = new Attack[maxCoords.X + 1, maxCoords.Y + 1]; for (int x = 0; x <= maxCoords.X; x++) { for (int y = 0; y <= maxCoords.Y; y++) { Attacks[x, y] = new Attack(); } } this.sph = new ShipPlacementHelper(maxCoords); this.gih = new GameInfoHelper(); this.resetShips.IsEnabled = false; this.resetShips.Visibility = Visibility.Hidden; InitializeGrids(); InitializeShips(); InitializePlayerInfo(); }
/// <summary> /// The tile constructor will know where it is on the grid, and is its a ship /// </summary> /// <param name="row">the row on the grid</param> /// <param name="col">the col on the grid</param> /// <param name="ship">what ship it is</param> public Tile(int row, int col, Ship ship) { _RowValue = row; _ColumnValue = col; _Ship = ship; }
private Uri GetImageForShip(Ship s) { return new Uri(gih.shipImageLoc[s.Name], UriKind.Relative); }
/// <summary> /// Sets the chosen ship based on the button selected, if the ship cannot legally be placed on chosen button, an error message is shown /// </summary> /// <param name="ship">The ship to be placed</param> /// <param name="index">The index of the button chosen in the button field</param> /// <param name="orientation">The orientation of the ship to be placed</param> /// <param name="isRandomized">Whether or not the player chose to randomize the ship placement</param> public bool setShip(Ship ship, int index, Orientation orientation, bool isRandomized = false, bool isComputerPlacement = false) { int size = ship.size; int[] chosenButtonIndexes = new int[size]; // Orientation is horizontal if (orientation.Equals(Orientation.HORIZONTAL)) { // If placed in two rows if (((index + (size - 1)) % 10 < size - 1)) { int counter = 0; int reverseCounter = 1; while ((index + counter) % 10 > 1) { chosenButtonIndexes[counter] = index + counter; counter++; } for (int i = counter; i < size; i++) { chosenButtonIndexes[i] = index - reverseCounter; reverseCounter++; } } // If placed in one row else { for (int i = 0; i < size; i++) { chosenButtonIndexes[i] = index + i; } } } // Orientation is vertical else { // If placed in two columns if (index + (size * 10) > 100) { int counter = 0; int reverseCounter = 10; while ((index / 10 + counter) % 100 < 10) { chosenButtonIndexes[counter] = index + counter * 10; counter++; } for (int i = counter; i < size; i++) { chosenButtonIndexes[i] = index - reverseCounter; reverseCounter += 10; } } // If placed in one column else { for (int i = 0; i < size; i++) { chosenButtonIndexes[i] = index + (i * 10); } } } bool isValidPlacement = true; // Invalid placement check for (int i = 0; i < size; i++) { if (buttons[chosenButtonIndexes[i]].Tag != null) { isValidPlacement = false; } } if (isValidPlacement) { // Sort array Array.Sort(chosenButtonIndexes); // Update ship ship.orientation = orientation; ship.location = new List<int>(chosenButtonIndexes); ship.placed = true; if (!isComputerPlacement) { ship.item.IsEnabled = false; } // Set image // For some reason, if not done twice and ship is vertical, the image displayed is smaller than intended setImage(chosenButtonIndexes[0], ship, isComputerPlacement); setImage(chosenButtonIndexes[0], ship, isComputerPlacement); // Select buttons for (int i = 0; i < size; i++) { buttons[chosenButtonIndexes[i]].Tag = ship; if (!isComputerPlacement) { buttons[chosenButtonIndexes[i]].Opacity = 0; buttons[chosenButtonIndexes[i]].IsEnabled = false; } } } // Error if illegally placed else if (!isRandomized) { Console.Beep(500, 250); } return isValidPlacement; }
/// <summary> /// Clearship will remove the ship from the tile /// </summary> public void ClearShip() { _Ship = null; }
public void Initialize(Coordinate maxCoords, Ship[] startingShips) { this.wdw.Initialize(maxCoords, startingShips); wdw.ShipsPlaced += new MainWindow.ShipsPlacedEventHandler(HandlePiecePlaced); wdw.AttackMade += new MainWindow.AttackMadeEventHandler(HandleAttackMade); this.sph = new ShipPlacementHelper(maxCoords); }
/// <summary> /// Sets image of placed ship on button field /// </summary> /// <param name="index">The index of the first button chosen, where the front of the image will be placed</param> /// <param name="ship">The ship to be placed</param> /// <param name="orientation">The orientation of the ship</param> private void setImage(int index, Ship ship, bool isComputerPlacement) { // Copy image Image image = new Image(); image.Source = ship.image.Source; image.Stretch = ship.image.Stretch; // Set properties int span = ship.size; int row = Grid.GetRow(buttons[index]); int column = Grid.GetColumn(buttons[index]); Grid.SetRow(image, row); Grid.SetColumn(image, column); if (ship.orientation.Equals(Orientation.VERTICAL)) { // Rotate image image.LayoutTransform = new RotateTransform(90.0); Grid.SetRowSpan(image, span); image.Height = ship.image.Width; image.Width = ship.image.Height; } else { Grid.SetColumnSpan(image, span); image.Height = ship.image.Height; image.Width = ship.image.Width; } if (isComputerPlacement) { image.Visibility = System.Windows.Visibility.Hidden; } // Add image to location gameField.Children.Add(image); ship.image = new Image(); ship.image.Source = image.Source; ship.image.Stretch = image.Stretch; ship.image.Height = image.Height; ship.image.Width = image.Width; ship.image.LayoutTransform = image.LayoutTransform; Grid.SetRow(ship.image, row); Grid.SetColumn(ship.image, column); Grid.SetRowSpan(ship.image, Grid.GetRowSpan(image)); Grid.SetColumnSpan(ship.image, Grid.GetColumnSpan(image)); }
public int[] GetOpenLoc(Ship BS) { bool cantPos=false; int[] coords=new int[3]; Random R=new Random(); int size = BS.GetSize(); int times = 0; do { //Console.WriteLine("{0} try to find loc", times); times++; coords[0] = R.Next(0,10); coords[1] = R.Next(0,10); coords[2] = R.Next(0,2); if (coords[2] == 0) { int countSize = 0; int c=coords[1]; for (int r = coords[0]; r < coords[0]+size&&r<10; r++) { countSize++; if (board[r, c] == 1) { cantPos = true; break; } } if (countSize < size) cantPos = true; } else { int countSize = 0; for (int r = coords[0]; r == coords[0]; r++) { for (int c = coords[1]; c < coords[1] + size&&c<10; c++) { countSize++; if (board[r, c] == 1) { cantPos = true; break; } } if (cantPos) break; } if (countSize < size) cantPos = true; } if (times > 1000) { coords[0] = -1; break; } } while (cantPos); return coords; }
private void PlaceShip(Ship ship, PlaceShipDirection dir, int x, int y) { for (int i = 0; i < ship.Length; i++) { var p = this.Ocean[x, y]; p.Status = PointStatus.Ship; ship.Position.Add(p); if (dir == PlaceShipDirection.Horizontally) { x++; } else { y++; } } }
protected bool Equals(Ship other) { var lengthEquality = _length == other._length; var directionEquality = _direction == other._direction; var coordsEquality = _x == other._x && _y == other._y; if (!lengthEquality) return false; if (_length == 1 && coordsEquality) return true; return coordsEquality && directionEquality; }
/// <summary> /// ProcessDetroy is able to process the destroyed ships targets and remove _LastHit targets. /// It will also call RemoveShotsAround to remove targets that it was going to shoot at /// </summary> /// <param name="row">the row that was shot at and destroyed</param> /// <param name="col">the row that was shot at and destroyed</param> /// <param name="ship">the row that was shot at and destroyed</param> private void ProcessDestroy(int row, int col, Ship ship) { bool foundOriginal = false; Location source = null; Target current = null; current = _CurrentTarget; foundOriginal = false; //i = 1, as we dont have targets from the current hit... int i = 0; for (i = 1; i <= ship.Hits - 1; i++) { if (!foundOriginal) { source = current.Source; //Source is nnothing if the ship was originally hit in // the middle. This then searched forward, rather than // backward through the list of targets if (source == null) { source = current.ShotAt; foundOriginal = true; } } else { source = current.ShotAt; } //find the source in _LastHit foreach (Target t in _LastHit) { if ((!foundOriginal && t.ShotAt == source) || (foundOriginal & t.Source == source)) { current = t; _LastHit.Remove(t); break; // TODO: might not be correct. Was : Exit For } } RemoveShotsAround(current.ShotAt); } }
public virtual void Initialize(Coordinate maxCoords, Ship[] startingShips) { this.Ships = startingShips; this.Attacks = new Attack[maxCoords.X + 1, maxCoords.Y + 1]; for (int x = 0; x <= maxCoords.X; x++) { for (int y = 0; y <= maxCoords.Y; y++) { Attacks[x, y] = new Attack(); } } this.MaxCoords = maxCoords; this.sph = new ShipPlacementHelper(maxCoords); }