public void SetUp() { this.cells = new Dictionary <Point, Cell>(); for (var x = 0; x < this.width; x++) { for (var y = 0; y < this.height; y++) { var coordinate = new Point(x, y); var cell = new Cell(coordinate, this.cells); this.cells.Add(coordinate, cell); } } this.gameMap = new GameMap("TestPlayer", "OpponentPlayer", width, height); gameMap.Phase = 2; this.player = this.gameMap.GetBattleshipPlayer(PlayerType.One); this.opponent = this.gameMap.GetBattleshipPlayer(PlayerType.Two); this.playerMap = this.gameMap.GetPlayerMap(PlayerType.One); this.opponentMap = this.gameMap.GetPlayerMap(PlayerType.Two); PlacePlayerShips(); this.gameMap.Place(PlayerType.Two, ShipType.Battleship, new Point(1, 0), Direction.East); this.gameMap.Place(PlayerType.Two, ShipType.Carrier, new Point(0, 0), Direction.North); this.player.Energy = 50; }
public PlayerMap(int width, int height, BattleshipPlayer owner) : this() { if (width <= 0) { throw new ArgumentException("Argument cannot be zero or negative", nameof(width)); } if (height <= 0) { throw new ArgumentException("Argument cannot be zero or negative", nameof(width)); } for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var coordinate = new Point(x, y); var cell = new Cell(coordinate, this.cells); this.cells.Add(coordinate, cell); } } this.MapHeight = height; this.MapWidth = width; this.Owner = owner; }
public void fireAt(BattleshipPlayer opponent) { Console.WriteLine("Enter coordinate for fire"); bool IsPointValid = false; while (!IsPointValid) { try { Point point = new Point(Console.ReadLine()); int x = point.getX() - 1; int y = point.getY() - 1; Result result = ((Player1)opponent).GetBoard().GetField(x, y).shootAt(); if (result == Result.HIT || result == Result.DESTROYED) { totalLivesLeft--; } IsPointValid = true; } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e); } } }
public void PerformCommand(GameMap gameMap, BattleshipPlayer player) { try { if (player.Ships.Any(x => x.ShipType == ShipType.Carrier && !x.Destroyed)) { var opponentsMap = gameMap.GetOpponetMap(player.PlayerType); var cornerShot = opponentsMap.Cells.Where(cell => (cell.X + 1 == _centerPoint.X && cell.Y - 1 == _centerPoint.Y) || (cell.X - 1 == _centerPoint.X && cell.Y - 1 == _centerPoint.Y) || (cell.X + 1 == _centerPoint.X && cell.Y + 1 == _centerPoint.Y) || (cell.X - 1 == _centerPoint.X && cell.Y + 1 == _centerPoint.Y)).Select(x => new Point(x.X, x.Y)).ToList(); gameMap.Shoot(player.PlayerType, cornerShot, WeaponType.CornerShot); } else { throw new DestroyedShipException( $"{player.Name}'s Carrier has been destroyed and cannot use this shot"); } } catch (Exception exception) { throw new InvalidCommandException(exception.Message, exception); } }
public void PerformCommand(GameMap gameMap, BattleshipPlayer player) { try { var shotLanded = gameMap.Shoot(player.PlayerType, _point, WeaponType.SingleShot); player.ShotsFired++; if (shotLanded) { player.ShotsHit++; player.AddPoints(Settings.Default.PointsHit); if (player.FirstShotLanded == int.MaxValue) { player.FirstShotLanded = gameMap.CurrentRound; } } var destroyed = gameMap.WasShipDestroyed(player.PlayerType, _point); if (destroyed) { player.AddPoints(Settings.Default.PointsShipSunk); } } catch (Exception exception) { throw new InvalidCommandException(exception.Message, exception); } }
public void PerformCommand(GameMap gameMap, BattleshipPlayer player) { if (_ships == null || _points == null || _directions == null) { throw new InvalidCommandException($"There was a problem during the placement of player's {player} ships (Placement null), the round will be played over"); } if (_ships.Count != _maxNumOfShips || _points.Count != _maxNumOfShips || _directions.Count != _maxNumOfShips) { throw new InvalidCommandException($"There was a problem during the placement of player's {player} ships (Invalid placement count), the round will be played over"); } gameMap.CleanMapBeforePlace(player.PlayerType); var successfulPlace = true; for (var index = 0; index < _maxNumOfShips; index++) { var ship = _ships[index]; var point = _points[index]; var direction = _directions[index]; if (direction == null) { throw new InvalidCommandException($"A direction for {ship} is required for placement"); } try { successfulPlace = gameMap.CanPlace(player.PlayerType, ship, point, direction); } catch (Exception e) { throw new InvalidCommandException($"There was a problem during the placement of player's {player} ships, the round will be played over", e); } } if (!successfulPlace) { throw new InvalidCommandException($"There was a problem during the placement of player's {player} ships, the round will be played over"); } for (var index = 0; index < _maxNumOfShips; index++) { try { var ship = _ships[index]; var point = _points[index]; var direction = _directions[index]; if (direction == null) { throw new InvalidCommandException($"A direction for {ship} is required for placement"); } gameMap.Place(player.PlayerType, ship, point, direction); } catch (InvalidOperationException ioe) { throw new InvalidCommandException("There was an issue during the placement of the ships", ioe); } } }
protected void SetCommandTypeAndCenterPoint(ICommand command, BattleshipPlayer player) { if (command is FireSingleShotCommand) { player.CommandIssued = CommandType.FireSingleShot.ToString(); player.CommandCenterPoint = ((FireSingleShotCommand)command).Point; } else if (command is PlaceShipCommand) { player.CommandIssued = CommandType.PlaceShip.ToString(); player.PlaceShipString = ((PlaceShipCommand)command).OriginalString; } else if (command is PlaceShieldCommand) { player.CommandIssued = CommandType.PlaceShield.ToString(); player.CommandCenterPoint = ((PlaceShieldCommand)command).Point; } else if (command is FireSeekerMissileCommand) { player.CommandIssued = CommandType.FireSeekerMissile.ToString(); player.CommandCenterPoint = ((FireSeekerMissileCommand)command).CenterPoint; } else if (command is FireCornerrShotCommand) { player.CommandIssued = CommandType.FireCornerShot.ToString(); player.CommandCenterPoint = ((FireCornerrShotCommand)command).CenterPoint; } else if (command is FireCrossShotCommand) { if (((FireCrossShotCommand)command).Diagonal) { player.CommandIssued = CommandType.FireCrossShotDiagonal.ToString(); player.CommandCenterPoint = ((FireCrossShotCommand)command).CenterPoint; } else { player.CommandIssued = CommandType.FireCrossShotNormal.ToString(); player.CommandCenterPoint = ((FireCrossShotCommand)command).CenterPoint; } } else if (command is FireDoubleShotCommand) { if (((FireDoubleShotCommand)command).Direction == Direction.North || ((FireDoubleShotCommand)command).Direction == Direction.South) { player.CommandIssued = CommandType.FireDoubleShotVertical.ToString(); player.CommandCenterPoint = ((FireDoubleShotCommand)command).CenterPoint; } else { player.CommandIssued = CommandType.FireDoubleShotHorizontal.ToString(); player.CommandCenterPoint = ((FireDoubleShotCommand)command).CenterPoint; } } else { player.CommandIssued = CommandType.DoNothing.ToString(); } }
//CUSTOM FUNCTIONS //SINGLEPLAYER MODE private void SinglePlayer() { BattleshipPlayer player1 = new BattleshipPlayer("YOU", shipNumber); PlacementWindowOpen(player1); void PlacementWindowOpen(BattleshipPlayer player) { bool saved = false; Visible = false; // hiding this window BattleshipPlacement battleshipWindow1 = new BattleshipPlacement(shipNumber); //Event handling battleshipWindow1.OnPlacedAllShips += SaveInventory; battleshipWindow1.Show(); battleshipWindow1.FormClosed += new FormClosedEventHandler(GuessWindowOpen); void SaveInventory(object creator, BattleshipPlacement.PlacedAllShips f) { //SAVING INVENTORY player.myShips = new List <BattleshipShip>(f.inventory); player.myBoard = f.myBoard; saved = true; battleshipWindow1.OnPlacedAllShips -= SaveInventory; } void GuessWindowOpen(object s, EventArgs g) //OPENING THE SECOND PHASE { battleshipWindow1.FormClosed -= new FormClosedEventHandler(GuessWindowOpen); if (saved) { BattleshipGuessForm guessWndow = new BattleshipGuessForm(player); guessWndow.FormClosed += ShowThisWindow; guessWndow.Show(); guessWndow.Won += Won; void Won(object sender, BattleshipGuessForm.OnWin d) { guessWndow.Won -= Won; guessWndow.Close(); Visible = true; OnWinSingle(d.player); } void ShowThisWindow(object se, EventArgs e) { guessWndow.Won -= Won; guessWndow.FormClosed -= ShowThisWindow; Show(); } } else { Show(); } } } }
public void GivenName_WhenConstructing_SetsName() { var name = "TestName"; var player = new BattleshipPlayer(name, 'A', PlayerType.One, 10); Assert.AreEqual(name, player.Name); }
public void RequestShotFired(BattleshipPlayer player, Point locationOfShot) { if (_playerShotLocation.ContainsKey(player)) { throw new InvalidCommandException("Command Transaction already contains a destination shot for player " + player); } _playerShotLocation.Add(player, locationOfShot); }
public void PerformCommand(GameMap gameMap, BattleshipPlayer player) { try { if (player.Ships.Any(x => x.ShipType == ShipType.Submarine && !x.Destroyed)) { var opponentsMap = gameMap.GetOpponetMap(player.PlayerType); var occupiedCells = opponentsMap.Cells.Where(cell => cell.Occupied && !cell.Hit && !cell.Shielded).ToList(); var cellToHit = _centerPoint; if (occupiedCells.Any()) { var cellsInRange = occupiedCells.Select(x => new { distance = Math.Sqrt( Math.Pow((x.X - _centerPoint.X), 2) + Math.Pow(x.Y - _centerPoint.Y, 2)), cell = x }).OrderBy(x => x.distance); var cellInRange = cellsInRange.FirstOrDefault(x => x.distance < 1d); if (cellInRange == null) { cellInRange = cellsInRange.FirstOrDefault(x => x.distance < 1.4d); } if (cellInRange == null) { cellInRange = cellsInRange.FirstOrDefault(x => x.distance > 1.4d && x.distance < 2d); } if (cellInRange == null) { cellInRange = cellsInRange.FirstOrDefault(x => x.distance <= 2d); } cellToHit = cellInRange == null ? cellToHit : new Point(cellInRange.cell.X, cellInRange.cell.Y); } gameMap.Shoot(player.PlayerType, new List <Point> { cellToHit }, WeaponType.SeekerMissile); } else { throw new DestroyedShipException( $"{player.Name}'s Submarine has been destroyed and cannot use this shot"); } } catch (Exception exception) { throw new InvalidCommandException(exception.Message, exception); } }
public void GivenPlayer_WhenConstructing_AddsPlayerAsOwner() { var owner = new BattleshipPlayer("TestPlayer", 'A', PlayerType.One); const int width = 5; const int height = 5; var map = new PlayerMap(width, height, owner); Assert.AreEqual(owner, map.Owner); }
public void PerformCommand(GameMap gameMap, BattleshipPlayer player) { try { gameMap.PlaceShield(player, Point, gameMap.CurrentRound); } catch (Exception exception) { throw new InvalidCommandException(exception.Message, exception); } }
public void GivenMap_WhenPlacingShipOfOtherPlayer_ThrowsException() { const int width = 5; const int height = 5; var map = new PlayerMap(width, height, this.player); var coordinate = new Point(width / 2, height / 2); var otherPlayer = new BattleshipPlayer("OtherPlayer", 'A', PlayerType.One); var ship = ShipStub.FullStub(otherPlayer); Assert.Throws <InvalidOperationException>(() => map.Place(ship, coordinate, Direction.East)); }
public void GivenMap_WhenShootingWeaponAtCoordinatesOutsideOfMap_ThrowsException() { const int width = 5; const int height = 5; var map = new PlayerMap(width, height, this.player); var coordinate = new Point(-1, -1); var otherPlayer = new BattleshipPlayer("OtherPlayer", 'A', PlayerType.One); var weapon = new WeaponStub(otherPlayer); Assert.Throws <ArgumentException>(() => map.Shoot(coordinate, weapon)); }
protected Ship(BattleshipPlayer owner, int segmentCount, ShipType shipType) : this() { this.ShipType = shipType; this.Owner = owner; if (segmentCount <= 0) { throw new ArgumentException("Ship can't have zero or negative cells", nameof(segmentCount)); } this._cells = new Cell[segmentCount]; }
public void GivenNewPlayer_WhenConstructing_AddsAllShips() { var name = "TestName"; var player = new BattleshipPlayer(name, 'A', PlayerType.One, 10); Assert.IsNotNull(player.Battleship); Assert.IsNotNull(player.Carrier); Assert.IsNotNull(player.Cruiser); Assert.IsNotNull(player.Destroyer); Assert.IsNotNull(player.Submarine); }
protected Ship(BattleshipPlayer owner, int segmentCount, ShipType shipType, Weapon weapon) : this() { this.ShipType = shipType; this.Owner = owner; if (segmentCount <= 0) { throw new ArgumentException("Ship can't have zero or negative cells", nameof(segmentCount)); } this.Weapons = new List <Weapon> { new SingleShotWeapon(Owner, 1, WeaponType.SingleShot), weapon }; this._cells = new Cell[segmentCount]; }
public void GivenMap_WhenShootingWeaponAtCoordinatesInMap_CallsShootOnWeapon() { const int width = 5; const int height = 5; var map = new PlayerMap(width, height, this.player); var coordinate = new Point(width / 2, height / 2); var otherPlayer = new BattleshipPlayer("OtherPlayer", 'A', PlayerType.One); var weapon = new WeaponStub(otherPlayer); map.Shoot(coordinate, weapon); Assert.True(weapon.ShootCalled); Assert.NotNull(weapon.Target); }
public void PerformCommand(GameMap gameMap, BattleshipPlayer player) { try { gameMap.Shoot(player.PlayerType, new List <Point>() { Point }, WeaponType.SingleShot); } catch (Exception exception) { throw new InvalidCommandException(exception.Message, exception); } }
private void RunBotAndGetNextMove() { if (_totalDoNothingCommands >= 10) { Logger.LogInfo( "Bot is sending to many do nothing commands, if this continues it the bot will be killed off"); } if (_totalDoNothingCommands >= 20) { BotUnresponsive(); Logger.LogInfo( "Bot sent to many do nothing commands, something is most likely going wrong, please fix your bot. The player's ships will all be marked as destroyed and killed off."); BattleshipPlayer.Killoff(); } if (BattleshipPlayer.FailedFirstPhaseCommands == 5) { Logger.LogInfo("Bot has failed to place ships in the last 5 rounds and will be killed off"); BattleshipPlayer.Killoff(); } ICommand command; try { _botRunner.RunBot(); command = _botRunner.GetBotCommand(); } catch (TimeLimitExceededException ex) { Logger.LogException("Bot time limit exceeded ", ex); command = new DoNothingCommand(); } if (command.GetType() == typeof(DoNothingCommand)) { _totalDoNothingCommands++; } else { _totalDoNothingCommands = 0; } WriteLogs(); RemoveCommandFile(true); BotCommandPublished(command); PublishCommand(command); }
public void PlaceShield(BattleshipPlayer player, Point centerPoint, int currentRound) { if (player.Shield.Active) { throw new Exception("A shiled is already active and cant be placed"); } if (player.Shield.CurrentCharges == 0) { throw new Exception("The shield has no charge and cannot be applied"); } var playerMap = _playersMaps[player.PlayerType]; playerMap.PlaceShield(centerPoint, currentRound); }
public void SetUp() { this.cells = new Dictionary <Point, Cell>(); for (var x = 0; x < this.width; x++) { for (var y = 0; y < this.height; y++) { var coordinate = new Point(x, y); var cell = new Cell(coordinate, this.cells); this.cells.Add(coordinate, cell); } } this.player = new BattleshipPlayer("TestPlayer", 'A', PlayerType.One); }
public GameMap(string playerOneName, string playerTwoName, int mapWidth, int mapHeight) : this() { this.MapSize = mapHeight; this.RegisteredPlayers = new List <BattleshipPlayer>(); var playerOne = new BattleshipPlayer(playerOneName, 'A', PlayerType.One, mapHeight); var playerTwo = new BattleshipPlayer(playerTwoName, 'B', PlayerType.Two, mapHeight); this._players[PlayerType.One] = playerOne; this._players[PlayerType.Two] = playerTwo; var playerOneMap = new PlayerMap(mapWidth, mapHeight, playerOne); var playerTwoMap = new PlayerMap(mapWidth, mapHeight, playerTwo); this._opponentMaps[PlayerType.One] = playerTwoMap; this._opponentMaps[PlayerType.Two] = playerOneMap; this._playersMaps[PlayerType.One] = playerOneMap; this._playersMaps[PlayerType.Two] = playerTwoMap; this.Phase = 1; }
//DISPLAY WIN private void OnWinSingle(BattleshipPlayer winner) { ChangeView(menu, win); winnerLb.Text = winner.name + " WON!"; List <List <string> > sum = new List <List <string> >(); //INSERTING DATA TO THE TABLE try { if (SqlConnectionHandler.InitialSetup() == 0) { if (winner.name != "BOT") { SqlConnectionHandler.RunNonQuery($"INSERT INTO battleship(score) VALUES(1)"); } else { SqlConnectionHandler.RunNonQuery($"INSERT INTO battleship(score) VALUES(-1)"); } } //GETTING STATS sum = SqlConnectionHandler.Query($"SELECT sum(score) FROM battleship WHERE score = 1"); if (sum.Count > 0) { string ammount = Convert.ToString(sum[0][0]); winStatisticsLabel.Text = "Wins against bot: " + ammount; } else { winStatisticsLabel.Hide(); } } catch { winStatisticsLabel.Hide(); } }
public void PerformCommand(GameMap gameMap, BattleshipPlayer player) { try { if (player.Ships.Any(x => x.ShipType == ShipType.Destroyer && !x.Destroyed)) { var doubleShot = new List <Point>(); var opponentMap = gameMap.GetOpponetMap(player.PlayerType); if (Direction == Direction.North || Direction == Direction.South) { doubleShot = opponentMap.Cells .Where(cell => (cell.X == CenterPoint.X && cell.Y + 1 == CenterPoint.Y) || (cell.X == CenterPoint.X && cell.Y - 1 == CenterPoint.Y)) .Select(x => new Point(x.X, x.Y)).ToList(); } else if (Direction == Direction.East || Direction == Direction.West) { doubleShot = opponentMap.Cells .Where(cell => (cell.X + 1 == CenterPoint.X && cell.Y == CenterPoint.Y) || (cell.X - 1 == CenterPoint.X && cell.Y == CenterPoint.Y)) .Select(x => new Point(x.X, x.Y)).ToList(); } gameMap.Shoot(player.PlayerType, doubleShot, WeaponType.DoubleShot); } else { throw new DestroyedShipException( $"{player.Name}'s Battleship has been destroyed and cannot use this shot"); } } catch (Exception exception) { throw new InvalidCommandException(exception.Message, exception); } }
public DiagonalCrossShotWeapon(BattleshipPlayer owner, int energyRequired, WeaponType weaponType) : base(owner, energyRequired, weaponType) { }
public void initialize(BattleshipPlayer op1, BattleshipPlayer op2, Size boardSize, params int[] shipSizes) { if (op1 == null) throw new ArgumentNullException("op1"); if (op2 == null) throw new ArgumentNullException("op2"); if (boardSize == null) { boardSize = new Size(10, 10); } if (boardSize.Width <= 2 || boardSize.Height <= 2) throw new ArgumentOutOfRangeException("boardSize"); if (shipSizes == null || shipSizes.Length < 1) { this.useModels = true; this.shipSizes = null; } else { if (shipSizes.Where(s => s <= 0).Any()) throw new ArgumentOutOfRangeException("shipSizes"); if (shipSizes.Max() > boardSize.Width && shipSizes.Max() > boardSize.Height) throw new ArgumentOutOfRangeException("shipSizes"); if (shipSizes.Length > boardSize.Width && shipSizes.Length > boardSize.Height) throw new ArgumentOutOfRangeException("shipSizes"); this.shipSizes = new List<int>(shipSizes); this.useModels = false; } this.opponents = new List<BattleshipPlayer>(); this.opponents.Add(op1); this.opponents.Add(op2); this.boardSize = boardSize; var rand = new System.Random(); if (rand.Next(2) == 1) { currentplayer = playerone; } else { currentplayer = playertwo; } opponents[playerone].Score = 0; opponents[playertwo].Score = 0; if (useModels) { opponents[playerone].init(boardSize, true); opponents[playertwo].init(boardSize, false); } else { opponents[playerone].init(boardSize, true,shipSizes); opponents[playertwo].init(boardSize, false,shipSizes); } opponents[currentplayer].StartTurn(); gameStarted = true; gameOver = false; }
public void SetUp() { this.player = new BattleshipPlayer("SomePlayer", 'A', PlayerType.One); }
public DoubleShotWeapon(BattleshipPlayer owner, int energyRequired, WeaponType weaponType) : base(owner, energyRequired, weaponType) { }
public SingleShotWeapon(BattleshipPlayer owner) : base(owner) { }