public static void Main(string[] args) { var ships = new IShip[] { new Battleship(), new Destroyer(), new Destroyer() }; var battlegrid = new RandomisedBattlegridBuilder() .Build(10, 10, ships); var sunkCount = 0; do { var line = Console.ReadLine(); if (line != null && line.Equals("cheat", StringComparison.OrdinalIgnoreCase)) { WriteCheatInfo(battlegrid); continue; } var position = ParsePosition(line); var result = battlegrid.LaunchPebble(position); if (result == StrikeResult.Hit) Console.WriteLine("Your pebble scored a hit!"); if (result == StrikeResult.FullySunk) { sunkCount++; Console.WriteLine("Rejoice commander! You've sunk a ship by throwing pebbles at it!"); } if (result == StrikeResult.Miss) Console.WriteLine("We're throwing pebbles whilst blind, commander!"); } while (sunkCount < ships.Length); Console.WriteLine("You win!!!"); Console.ReadKey(); }
public void AddShip(Fleet fleet, IShip ship) { if (fleet == Fleet.Red) redShips.Add(ship); else blueShips.Add(ship); }
public Player(PlayerIndex playerIndex, IShip ship, Island homeIsland, Map map) { this.playerIndex = playerIndex; this.ship = ship; this.homeIsland = homeIsland; this.map = map; }
public override bool Buy(TypeOFBullets bullet, IShip ship, IPlayer player) { if (bullet == TypeOFBullets.Kamikaze && ship[TypeOfGun.RocketGun] && ship.NumOfCrazyAlbatroses < 1) { ship.NumOfCrazyAlbatroses++; player.Money -= shop.GetPrice(TypeOFBullets.Kamikaze.ToString()); return true; } if (bullet == TypeOFBullets.SuperRocket && ship[TypeOfGun.RocketGun] && ship.NumOfSuperRockets < 3) { ship.NumOfSuperRockets++; player.Money -= shop.GetPrice(TypeOFBullets.SuperRocket.ToString()); return true; } else if (bullet == TypeOFBullets.BarrelBurn && ship[TypeOfGun.Catapult] && ship.NumOfFireBarrels < 5) { ship.NumOfFireBarrels++; player.Money -= shop.GetPrice(TypeOFBullets.BarrelBurn.ToString()); return true; } else if (bullet == TypeOFBullets.RottenFish && ship[TypeOfGun.Catapult] && ship.NumOfFishBarrels < 5) { ship.NumOfFishBarrels++; player.Money -= shop.GetPrice(TypeOFBullets.RottenFish.ToString()); return true; } else if (bullet == TypeOFBullets.Bomb && ship[TypeOfGun.CannonGun] && ship.NumOfBombs < 5) { ship.NumOfBombs++; player.Money -= shop.GetPrice(TypeOFBullets.Bomb.ToString()); return true; } return false; }
public static bool Collide(IShip shipColliding, IProjectile ball) { Rectangle shipRect = new Rectangle( (int)shipColliding.Position.X + COLLISION_OFFSET, (int)shipColliding.Position.Y + COLLISION_OFFSET, shipColliding.FrameSize.X - (COLLISION_OFFSET * 2), shipColliding.FrameSize.Y - (COLLISION_OFFSET * 2)); Rectangle cannonBall = new Rectangle( (int)ball.Position.X + COLLISION_OFFSET, (int)ball.Position.Y + COLLISION_OFFSET, ball.FrameSize.X - (COLLISION_OFFSET * 2), ball.FrameSize.Y - (COLLISION_OFFSET * 2)); if (shipRect.Intersects(cannonBall)) { ball.Position = new Vector2(9999,9999); // might be buggy return true; } if (ball.Position.Y >= ball.BallFiredPos.Y) { ball.Position = new Vector2(999,999); } return false; }
internal Shield(IShip ship, float maxLevel, float rechargeRate) { _ship = ship; _maxLevel = maxLevel; _rechargeRate = rechargeRate; Level = maxLevel; }
/// <summary> /// Get a reference to the ship, then put the camera in the ideal starting position. /// </summary> void Start() { ship = registry.LookUp<IShip>("Ship"); // start the camera out in the ideal position UpdateIdealPosition(); transform.position = idealPosition; transform.LookAt(ship.transform.position, ship.transform.up); }
public ShipGoldView(Game game, IShip ship, GoldViewPosition position , SpriteBatch spriteBatch, float displayWidth) : base(game) { this.ship = ship; this.spriteBatch = spriteBatch; this.displayWidth = displayWidth; scale = 1f; this.DisplayCorner = position; }
public Battlegrid Add(IShip ship, Position position, Orientation orientation) { if (ship == null) throw new ArgumentNullException("ship"); if (ship.Owner != null) throw new ShipOwnedByAnotherBattlegridException(); ship.Position = position; ship.Orientation = orientation; Add(ship); return this; }
public void MoveShip(GamePadState gs, IShip ship) { if (gs.ThumbSticks.Left != Vector2.Zero) { if (gs.ThumbSticks.Left.Y > 0) { ship.Accelerate(gs.ThumbSticks.Left.Y * 10); } ship.Rotate(gs.ThumbSticks.Left.X * 20); } }
/// <summary> /// An AIController should have access to all information a user of the system has. /// </summary> /// <param name="game">The game</param> /// <param name="controlledShip">The ship that the AI is controlling</param> /// <param name="homeIsland">The ship's home island</param> /// <param name="islands">All islands in the game(excluding the ships home island)</param> public AIController(Game game, IShip controlledShip, Island homeIsland, List<Island> otherIslands, IShip targetShip) : base(game) { this.ControlledShip = controlledShip; this.HomeIsland = homeIsland; this.OtherIslands = otherIslands; this.ProximityRadius = 50.0f; this.TargetShip = targetShip; }
public Battlegrid Add(IShip ship) { if (ship == null) throw new ArgumentNullException("ship"); if (ship.Owner != null) throw new ShipOwnedByAnotherBattlegridException(); _map.Add(ship); _ships.Add(ship); ship.Owner = this; return this; }
public void Add(IShip ship) { switch (TryAddCore(ship)) { case HitType.ExistingShip: throw new ShipConflictBattlegridException(); case HitType.GridBoundaries: throw new ShipOffTheBattlegridException(); default: return; } }
/// <summary> /// /// </summary> /// <param name="game"></param> /// <param name="shipColor">The color that the highlights on the ship should be drawn.</param> /// <param name="contentName"></param> /// <param name="scale"></param> /// <param name="color"></param> /// <param name="spriteBatch"></param> /// <param name="gameObject">The game object that this is a view for. Must be of type Ship.</param> public ShipView(Game game, Color shipOutlineColor, Content content, Color color, SpriteBatch spriteBatch, IShip ship) : base(game, content, color, spriteBatch, ship, ZIndexManager.getZIndex(ZIndexManager.drawnItemOrders.shipHull)) { this.shipOutlineColor = shipOutlineColor; this.ship = ship; ship.ObjectDestroyed += this.ShipSankEventHandler; healthBarView = new HealthBarView(base.Game, spriteBatch, ship); Game.Components.Add(healthBarView); LeftCannonView = new CannonView(Game, Color.White, SpriteBatch, ship.LeftCannons.First()); RightCannonView = new CannonView(Game, Color.White, SpriteBatch, ship.RightCannons.First()); }
public void TestMove() { // Arrange _unitUnderTest = new DefaultPlayer(new Point(100, 100)); // Act _unitUnderTest.Move(Direction.Right); // Assert var shouldArriveHerePoint = new Point(120, 100); Assert.That(_unitUnderTest.Rect.Location, Is.EqualTo(shouldArriveHerePoint)); }
public static void Draw(Graphics g1, IShip tempShip, double timer, Commander tempCommander) { Single textRight = 1050f; PointF direction = new PointF(textRight, 15f); PointF X_Cord = new PointF(textRight, 30f); PointF Y_Cord = new PointF(textRight, 45f); PointF Engines = new PointF(textRight, 60f); PointF Time = new PointF(textRight, 75f); Brush ShieldPowerBrush = Brushes.Green; //Decide the colour of the sheild bar based on the ship power if (tempShip.ShieldPower > 80) { ShieldPowerBrush = Brushes.Green; } else if (tempShip.ShieldPower > 60) { ShieldPowerBrush = Brushes.YellowGreen; } else if (tempShip.ShieldPower > 40) { ShieldPowerBrush = Brushes.Yellow; } else if (tempShip.ShieldPower > 20) { ShieldPowerBrush = Brushes.OrangeRed; } else if (tempShip.ShieldPower > 1) { ShieldPowerBrush = Brushes.Red; } // Draw the UI using (Font arialFont = new Font("Arial", 10)) { g1.DrawString("Level:" + tempCommander.SelectedLevel.ToString(), arialFont, Brushes.Red, new PointF(textRight, 1f)); g1.DrawString("Direction:" + tempShip.direction.ToString(), arialFont, Brushes.Red, direction); g1.DrawString("X Cord:" + tempShip.Position.X.ToString(), arialFont, Brushes.Red, X_Cord); g1.DrawString("Y Cord:" + tempShip.Position.Y.ToString(), arialFont, Brushes.Red, Y_Cord); g1.DrawString("Engines:" + tempShip.Engines.ToString(), arialFont, Brushes.Red, Engines); g1.DrawString("Tick:" + timer.ToString(), arialFont, Brushes.Red, Time); //Power and power bar stuff g1.FillRectangle(ShieldPowerBrush, textRight, 110, tempShip.ShieldPower, 10); g1.DrawString("Ship Power:", arialFont, Brushes.Red, new PointF(textRight, 91f)); } }
internal ThrusterArray(IShip ship) { _ship = ship; var forwardThrust = new Vector2(0, -ThrustPower); var backthrust = new Vector2(0, ThrustPower); var leftOfShip = new Vector2(-ship.Radius, 0); var rightOfShip = new Vector2(ship.Radius, 0); _frontLeftThruster = new Thruster(leftOfShip, forwardThrust, ThrustEnergyCost); _frontRightThruster = new Thruster(rightOfShip, forwardThrust, ThrustEnergyCost); _backLeftThruster = new Thruster(leftOfShip, backthrust, ThrustEnergyCost); _backRightThruster = new Thruster(rightOfShip, backthrust, ThrustEnergyCost); }
/// <summary> /// Get the island that is closest to the ship and within range. /// </summary> /// <param name="ship"></param> /// <param name="range">Minimum range to look for islands.</param> /// <returns>The closest island if one exists, otherwise null.</returns> public Island GetClosestInRangeIsland(IShip ship, float range) { Island closestIsland = ClosestIslandToPoint(ship.Position); // We only want the closest island if it is in range if (closestIsland != null && DistanceToIsland(ship.Position, closestIsland) <= range) { return closestIsland; } else { return null; } }
public HitType HitTest(Position position, bool recordHit, out IShip ship) { if (position.X >= _map.GetLength(0) || position.Y >= _map.GetLength(1)) { ship = null; return HitType.GridBoundaries; } ship = _map[position.X, position.Y]; if (ship != null) { if (recordHit) _map[position.X, position.Y] = null; return HitType.ExistingShip; } return HitType.None; }
private IEnumerable<Position> GetCells(IShip ship) { switch (ship.Orientation) { case Orientation.Horizontal: return Enumerable .Range(ship.Position.X, ship.Length) .Select(coordX => new Position(coordX, ship.Position.Y)); case Orientation.Vertical: return Enumerable .Range(ship.Position.Y, ship.Length) .Select(coordY => new Position(ship.Position.X, coordY)); default: throw new InvalidOperationException("The orientation of the ship is invalid."); } }
public void Add(IShip ship) { foreach (var shipOnBoard in _shipsOnBoard) { if (ship.OverlapsWith(shipOnBoard)) throw new ShipOverlapException($"Ship {ship.GetNotation()} overlaps with {shipOnBoard.GetNotation()}"); } var endX = ship.Direction == Direction.Vertical ? 0 : ship.Length - 1; var endY = ship.Direction == Direction.Vertical ? ship.Length - 1 : 0; if (ship.X > 10 || ship.Y > 10 || ship.Y < 0 || ship.Y > 10) throw new ArgumentOutOfRangeException(); if (ship.X + endX > 10 || ship.Y + endY > 10) throw new ArgumentOutOfRangeException(); _shipsOnBoard.Add(ship); }
public UnitViewModel(IShip ship, double cheaperFleetModifier = 0) { this.Name = ship.Name; this.Description = ship.Description; this.Attack = ship.Attack; this.Armor = ship.Armor; this.BuildTime = ship.BuildTime.TotalMinutes; this.CargoCapacity = ship.CargoCapacity; this.Prerequisite = ship.Prerequisite; this.PointsOnRecruit = ship.PointsOnRecruit; this.PointsOnKill = ship.PointsOnKill; var requiredResources = ship.RequiredResourcesToBuild; this.RequiredEnergy = requiredResources[0] - (int)(cheaperFleetModifier * requiredResources[0]); this.RequiredCrystals = requiredResources[1] - (int)(cheaperFleetModifier * requiredResources[1]); this.RequiredMetal = requiredResources[2] - (int)(cheaperFleetModifier * requiredResources[2]); }
public static BattleResult Fight(IShip red, IShip blue) { // determine two combat numbers: double redCombat = rand.NextDouble(); double blueCombat = rand.NextDouble(); redCombat += red.CombatModifier; blueCombat += blue.CombatModifier; // Console.WriteLine("Red Number: " + redCombat); // Console.WriteLine("Blue Number: " + blueCombat); if(redCombat.IsApproximatelyEqualTo(blueCombat)) return new BattleResult(null, red, blue); return redCombat > blueCombat ? new BattleResult(Fleet.Red, red, blue) : new BattleResult(Fleet.Blue, red, blue); }
public override bool Buy(TypeOfGun gun, IShip ship, IPlayer player) { IWeapon weapon = shop.GetProduct(gun); if (weapon != null) { ship.SetWeaponFromShop(weapon.GunType, weapon); player.Money -= shop.GetPrice(gun.ToString()); if (gun == TypeOfGun.Catapult) { ship.NumOfStones = 5; } else { ship.NumOfRockets = 5; } return true; } return false; }
public static void ExtractEffect(IShip targetShip, BonusType type) { switch (type) { case BonusType.Freeze: targetShip.Freeze(); break; case BonusType.Damage: targetShip.BonusDamage(); break; case BonusType.Wind: targetShip.Wind(); break; case BonusType.Null: break; //default: // throw new ArgumentOutOfRangeException(nameof(type), type, null); } }
public static void ExtractEffect(IShip targetShip, PotionTypes type) { switch (type) { case PotionTypes.Energy: targetShip.Energy += (int)type; break; case PotionTypes.Health: targetShip.Health += (int)type; break; case PotionTypes.Shields: targetShip.Shields += (int)type; break; case PotionTypes.Null: break; //default: // throw new ArgumentOutOfRangeException(nameof(type), type, null); } }
public void PlaceShip(IShip ship) { int shipRow = ship.TopLeft.Row; int shipCol = ship.TopLeft.Col; for (int i = 0; i < ship.Size; i++) { this.grid[shipRow, shipCol] = ship.Image; if (ship.Direction == ShipDirection.Vertical) { shipRow++; } else { shipCol++; } } }
public bool PlaceShip(IShip ship) { List<ICell> cellsToPlace = new List<ICell>(); ship.Decks.ForEach(deck => cellsToPlace.Add(cells[deck.X, deck.Y])); if (cellsToPlace.Any(cell => cell.IsOccupied)) { return false; } for (int i = 0; i < cellsToPlace.Count; i++) { ICell current = cellsToPlace[i]; current.Content = ship.Decks[i]; OccupyAround(current); } return true; }
public bool PlaceShip(IPlayer player, Location location, ShipType shipType, ShipLayout layout) { IBoard board = _boardByPlayer[player]; var ships = _shipByPlayer[player]; if (!board.TryPlaceShip(location, shipType, layout)) { return(false); } IShip ship = ShipFactory.CreateShip(board, location, shipType, layout, _battleshipConfig.ShipSizeByType); ship.Owner = player.ID; ships.Add(ship); foreach (var cell in ship.Cells) { cell.HasShip = true; } return(true); }
private void CheckVerticalOrientation(IShip ship, ref int x, ref int y, ref bool success) { y = GenerateCoordinate(ship.Size); x = GenerateCoordinate(); for (int i = 0; i < ship.Size; i++) { if (cells[x, y + i].Symbol != null) { success = false; break; } } if (success) { for (int i = 0; i < ship.Size; i++) { cells[x, y + i].Symbol = '+'; } } }
private void DrawVulnerableSectors(Graphics graphics, IShip ship) { var pen = VulnerableSectors.Select(OwnShip, ship); bool isMyShip = ship == OwnShip; bool isFriendlyShip = !isMyShip && (OwnShip != null && OwnShip.Nation == ship.Nation); bool isHostileShip = (OwnShip != null && OwnShip.Nation != ship.Nation); var range = (isMyShip || isFriendlyShip || OwnShip == null || OwnShip != null) ? Catalog.Instance.MaximumMissileRange : OwnShip.MissileRange(); if (Options.HasFlag(DrawingOptions.FriendlySectorsByMyMissileRange) && OwnShip != null && OwnShip.Class != null) { range = OwnShip.MissileRange(); } if ((isMyShip && !Options.HasFlag(DrawingOptions.MyVulnerableSectors)) || (isFriendlyShip && !Options.HasFlag(DrawingOptions.FriendlyVulnerableSectors)) || (isHostileShip && !Options.HasFlag(DrawingOptions.HostileVulnerableSectors))) { return; } WorldDrawPie(graphics, pen, ship.Position, range, ship.Heading, Catalog.Instance.ThroatAngle); WorldDrawPie(graphics, pen, ship.Position, range, ship.Heading - Math.PI, Catalog.Instance.SkirtAngle); }
public static bool Collide(IShip shipColliding, ISpecialty specialtyItem) { Rectangle shipRect = new Rectangle( (int)shipColliding.Position.X + OFFSET, (int)shipColliding.Position.Y + OFFSET, shipColliding.FrameSize.X - (OFFSET * 2), shipColliding.FrameSize.Y - (OFFSET * 2)); Rectangle mineRectangle = new Rectangle( (int)specialtyItem.Position.X + OFFSET, (int)specialtyItem.Position.Y + OFFSET, specialtyItem.FrameSize.X - (OFFSET * 2), specialtyItem.FrameSize.Y - (OFFSET * 2)); if (shipRect.Intersects(mineRectangle)) { specialtyItem.Position = new Vector2(9999, 9999); // might be buggy return true; } return false; }
public AttackMessage GetAttackOnFieldResult(int i, int j) { cellField[i, j].Explored = true; IShip ship = GetShipByIJCoordinates(i, j); if (ship == null) { return(new AttackMessage(AttackResult.Miss, i, j)); } else { if (ship.Attack() == AttackResult.Destroy) { ShipDestroyed(ship); return(new AttackMessage(AttackResult.Destroy, i, j, ship)); } else { return(new AttackMessage(AttackResult.Hit, i, j)); } } }
public void FindShipAtCoordinate_ShouldReturnNullWhenNoShipOccupiesTheCoordinate() { AssertContains5Ships(); //Arrange Mock <IShip>[] shipMocks = ReplaceShipsWithMocks(); GridCoordinate coordinate = new GridCoordinateBuilder().Build(); //Act IShip result = _fleet.FindShipAtCoordinate(coordinate); //Act + Assert Assert.That(result, Is.Null); foreach (Mock <IShip> shipMock in shipMocks) { IShip ship = shipMock.Object; shipMock.Verify(s => s.CanBeFoundAtCoordinate(coordinate), Times.Once, $"The CanBeFoundAtCoordinate of the Ship is not called for the '{ship.Kind.Name}'. " + $"Each ship must be checked."); } }
public override void OnShow(object msg) { base.OnShow(msg); if (m_ShipProxy == null) { m_ShipProxy = GameFacade.Instance.RetrieveProxy(ProxyName.ShipProxy) as ShipProxy; } if (m_PackageProxy == null) { m_PackageProxy = GameFacade.Instance.RetrieveProxy(ProxyName.PackageProxy) as PackageProxy; } if (msg != null) { m_LastPanelShip = (IShip)msg; } m_Parent.OnEscClick = OnEscClick; State.GetAction(UIAction.Hangar_Assemble).Callback -= OnAssembleShip; State.GetAction(UIAction.Hangar_Assemble).Callback += OnAssembleShip; State.GetAction(UIAction.Hangar_Appoint).Callback -= OnAppointShip; State.GetAction(UIAction.Hangar_Appoint).Callback += OnAppointShip; }
public static bool Collide(IShip shipColliding) { Rectangle shipRect = new Rectangle( (int)shipColliding.Position.X + COLLISION_OFFSET, (int)shipColliding.Position.Y + COLLISION_OFFSET, shipColliding.FrameSize.X - (COLLISION_OFFSET * 2), shipColliding.FrameSize.Y - (COLLISION_OFFSET * 2)); Rectangle itemRect = new Rectangle( (int)Item.Position.X + COLLISION_OFFSET, (int)Item.Position.Y + COLLISION_OFFSET, Item.FrameSize.X - (COLLISION_OFFSET * 2), Item.FrameSize.Y - (COLLISION_OFFSET * 2)); if (shipRect.Intersects(itemRect)) { Item.Position = new Vector2(9900,9900); return true; } return false; }
public static bool Collide(IShip shipColliding) { Rectangle shipRect = new Rectangle( (int)shipColliding.Position.X + COLLISION_OFFSET, (int)shipColliding.Position.Y + COLLISION_OFFSET, shipColliding.FrameSize.X - (COLLISION_OFFSET * 2), shipColliding.FrameSize.Y - (COLLISION_OFFSET * 2)); Rectangle itemRect = new Rectangle( (int)Item.Position.X + COLLISION_OFFSET, (int)Item.Position.Y + COLLISION_OFFSET, Item.FrameSize.X - (COLLISION_OFFSET * 2), Item.FrameSize.Y - (COLLISION_OFFSET * 2)); if (shipRect.Intersects(itemRect)) { Item.Position = new Vector2(9900, 9900); return(true); } return(false); }
public static bool Collide(IShip shipColliding, ISpecialty specialtyItem) { Rectangle shipRect = new Rectangle( (int)shipColliding.Position.X + OFFSET, (int)shipColliding.Position.Y + OFFSET, shipColliding.FrameSize.X - (OFFSET * 2), shipColliding.FrameSize.Y - (OFFSET * 2)); Rectangle mineRectangle = new Rectangle( (int)specialtyItem.Position.X + OFFSET, (int)specialtyItem.Position.Y + OFFSET, specialtyItem.FrameSize.X - (OFFSET * 2), specialtyItem.FrameSize.Y - (OFFSET * 2)); if (shipRect.Intersects(mineRectangle)) { specialtyItem.Position = new Vector2(9999, 9999); // might be buggy return(true); } return(false); }
private void AttackNonDockedPlayership(IMap map, IShip badGuy, int randomFactor) { var playerShipLocation = map.Playership.GetLocation(); var distance = Utility.Utility.Distance(playerShipLocation.Sector.X, playerShipLocation.Sector.Y, badGuy.Sector.X, badGuy.Sector.Y); int seedEnergyToPowerWeapon = this.Config.GetSetting <int>("DisruptorShotSeed") * randomFactor; var inNebula = badGuy.GetRegion().Type == RegionType.Nebulae; //Todo: this should be Disruptors.For(this.ShipConnectedTo).Shoot() //todo: the -1 should be the ship energy you want to allocate var attackingEnergy = (int)Utility.Utility.ShootBeamWeapon(seedEnergyToPowerWeapon, distance, "DisruptorShotDeprecationLevel", "DisruptorEnergyAdjustment", inNebula); var shieldsValueBeforeHit = Shields.For(map.Playership).Energy; map.Playership.AbsorbHitFrom(badGuy, attackingEnergy); this.ReportShieldsStatus(map, shieldsValueBeforeHit); }
private bool ShipCanFit(List <Point> list, Point p, IShip ship) { int maxCoordX = 10 - (ship.Orientation == ShipPlacementOrientations.Horizontal ? ship.Size : 0); int maxCoordY = 10 - (ship.Orientation == ShipPlacementOrientations.Vertical ? ship.Size : 0); if (p.X > maxCoordX || p.X + ship.Size > 9) { return(false); } if (p.Y > maxCoordY || p.Y + ship.Size > 9) { return(false); } for (int i = 0; i < ship.Size; i++) { if (ship.Orientation == ShipPlacementOrientations.Horizontal) { if (!list.Contains(new Point() { X = p.X + i, Y = p.Y })) { return(false); } } else { if (!list.Contains(new Point() { X = p.X, Y = p.Y + i })) { return(false); } } } return(true); }
private bool ShipFits(IShip ship, int row, int column, Orientation orientation) { if (orientation == Orientation.Vertical) { if (row + ship.Size >= Rows) { return(false); } for (int i = 0; i < ship.Size; i++) { if (cells[row + i, column] == Cell.Ship) { return(false); } } } if (ShipFits(ship, row, column, orientation)) { if (orientation == Orientation.Horizontal) { if (column + ship.Size >= Columns) { return(false); } for (int i = 0; i < ship.Size; i++) { if (cells[row, column + i] == Cell.Ship) { return(false); } } } } return(true); }
public async Task InitializeAsync() { ready = false; ships.Clear(); JObject json = null; using (var httpClient = new HttpClient()) { var jsonraw = await httpClient.GetStringAsync("https://api.worldofwarships.com/wows/encyclopedia/ships/?application_id=ca60f30d0b1f91b195a521d4aa618eee"); json = JObject.Parse(jsonraw); } if ((String)json["status"] != "ok") { Console.WriteLine("Failed to obtain ship list."); ready = null; return; } JObject data = (JObject)json["data"]; foreach (JObject o in data.Values()) { IShip s = null; switch ((String)o["type"]) { case "AirCarrier": { s = new AirCarrier(MainHandler, o); break; } case "Battleship": { s = new DCB(MainHandler, o); break; } case "Cruiser": { s = new DCB(MainHandler, o); break; } case "Destroyer": { s = new DCB(MainHandler, o); break; } } //s.updateData(); ## com await demora mt, sem await ele dá errado -.- ships.Add((ClearShipName((String)o["name"])), s); } ready = true; }
public ShootResultDTO Shoot(int positionX, int positionY) { ShootResultDTO result = new ShootResultDTO() { PositionX = positionX, PositionY = positionY }; var hit = Fields[positionX, positionY].Shoot(); if (hit) { IShip shipHit = Ships.SingleOrDefault(x => x.TryToShoot(positionX, positionY)); if (shipHit != null) { result.IsShipHit = true; result.IsShipSunk = shipHit.IsSunk; } else { throw new GameLogicalException("Inconsistent fields on board and ships"); } } return(result); }
PurchaseResult GenerateSaleTransactionSequence(IShip sellingShip, Port purchasingPort, HashSet <int> statefulCargoIDs, ref List <CargoTransaction> transactionsToSchedule, ref float totalPrice) { var cargoToSell = sellingShip.Cargo.GetStatefulCargo(statefulCargoIDs.ToList()); if (cargoToSell.Count != statefulCargoIDs.Count) { return(PurchaseResult.CargoNotInHolds); } totalPrice += purchasingPort.Cargo.GetPrice(cargoToSell, PortTradeDirection.ShipSaleToPort); foreach (var i in statefulCargoIDs) { var fromShip = new TransactionRemoveStatefulCargo(sellingShip, StatefulCargoTypes.Null, i, true); var toPort = new TransactionAddStatefulCargo(purchasingPort, null, true); transactionsToSchedule.Add(fromShip); transactionsToSchedule.Add(toPort); } return(PurchaseResult.Success); }
public bool CanSetShip(IShip ship) { if (UnsettedShipsByLength[ship.Length - 1].Value <= 0) { return(false); } if (ship.Orientation == Orientation.Horizontal && ship.J + ship.Length > 10) { return(false); } if (ship.Orientation == Orientation.Vertical && ship.I + ship.Length > 10) { return(false); } foreach (var item in placedShips) { if (ship.IsIntersectWith(item)) { return(false); } } return(true); }
///<summary>Bliver kaldt når et skib bliver ødelagt</summary> public void OnShipDestroyed(IShip ship) { //Tjek om det er vores spiller som er død if (ship as PlayerShip != null) { shipPlayer = null; } //Fjern skibet fra vores liste shipsAll.Remove(ship); //Ik spørg hvorfor, men det giver en større eksplosion, vi var for dovne her til at lave en seperat større eksplosions prefab xd GetFXManager().ExplosionAtPos(ship.transform.position); GetFXManager().ExplosionAtPos(ship.transform.position); GetFXManager().ExplosionAtPos(ship.transform.position); GetFXManager().ExplosionAtPos(ship.transform.position); GetFXManager().ExplosionAtPos(ship.transform.position); GetFXManager().ExplosionAtPos(ship.transform.position); GetFXManager().ExplosionAtPos(ship.transform.position); //Slet det helt til sidst Destroy(ship.gameObject); }
public int GetWeaponIndexByUID(ulong uid) { ShipProxy shipProxy = GameFacade.Instance.RetrieveProxy(ProxyName.ShipProxy) as ShipProxy; IShip currentShip = shipProxy.GetAppointWarShip(); IWeaponContainer container = currentShip.GetWeaponContainer(); if (container != null) { IWeapon[] weapons = container.GetWeapons(); if (weapons != null) { for (int iWeapon = 0; iWeapon < weapons.Length; iWeapon++) { if (weapons[iWeapon].GetUID() == uid) { return(weapons[iWeapon].GetPos()); } } } } return(0); }
public void Work() { // For example - we have already known factory types. We can // read it from configuration or another source. var factoryTypes = new List <VehicleFactory.VehicleType>() { VehicleFactory.VehicleType.Civil, VehicleFactory.VehicleType.Millitary }; foreach (var factoryType in factoryTypes) { var factory = VehicleFactory.GetFactory(factoryType); IShip ship = factory.CreateShip(); ICar car = factory.CreateCar(); IHelicopter helicopter = factory.CreateHelicopter(); ship.Bell(); car.Horn(); helicopter.Respond(); Console.WriteLine(""); } }
public bool ValidateShipCanBePlaced(IShip ship, IBoardCell startingCell, IBoard board) { if (ship.Width <= 0) { _logger.LogError("The ship's width cannot be less than 1."); return(false); } if (ship.Orientation == Enumerations.OrientationType.Vertical && (ship.Width + startingCell.XCoordinate) > board.BoardCells.Max(x => x.XCoordinate)) { return(false); } if (ship.Orientation == Enumerations.OrientationType.Horizontal && (ship.Width + startingCell.YCoordinate) > board.BoardCells.Max(x => x.YCoordinate)) { return(false); } var listOfCellsAffected = ListOfCellsAffected(ship, startingCell, board); return(!listOfCellsAffected.Any(x => x.Occupied)); }
private void DrawShipWedge(Graphics graphics, IShip ship) { if (ship.Board() > 0.5) { return; } double size = WorldScale / 4; var pen = SignalPen; var points = new[] { WorldToDevice(graphics, ship.Position + Vector.Direction(ship.Heading + Math.PI / 4) * size), WorldToDevice(graphics, ship.Position + Vector.Direction(ship.Heading + Math.PI * 11 / 12) * size), WorldToDevice(graphics, ship.Position + Vector.Direction(ship.Heading - Math.PI * 11 / 12) * size), WorldToDevice(graphics, ship.Position + Vector.Direction(ship.Heading - Math.PI / 4) * size), }; if (!IsVisible(points)) { return; } graphics.DrawLine(pen, points[0], points[1]); graphics.DrawLine(pen, points[2], points[3]); }
private bool CheckValidPlacement(IShip ship, ShipPlacementOrientations orientation, int x, int y) { for (int i = 0; i < ship.Size; i++) { // get x,y coordinates based on ship orientation int xi = x + (orientation == ShipPlacementOrientations.Horizontal ? i : 0); int yi = y + (orientation == ShipPlacementOrientations.Vertical ? i : 0); // check if out of bounds if (xi < 0 || xi > _grid.GetLength(0) || yi < 0 || yi > _grid.GetLength(1)) { return(false); } // check for collision with another ship if (_grid[xi, yi] is IShip) { return(false); } } return(true); }
/*public static ShipInfo GetShipInfo() * { * return new ShipInfo("Chmmr Avatar", new CreateShipDelegate(Create)); * }*/ protected static IShip[] CreateSubShips(PhysicsState physicsstate, FactionInfo factionInfo) { int SatelliteCount = DefaultSubShips.Length; IShip[] subShips = new IShip[SatelliteCount]; int pos = 0; float da = MathHelper.PI * 2 / SatelliteCount; for (float angle = 0; angle < MathHelper.PI * 2; angle += da) { PhysicsState state = new PhysicsState(physicsstate); Vector2D direction = Vector2D.Rotate(angle, Vector2D.XAxis); state.Position.Linear += direction * (DefaultSatelliteOrbitRadius + 1); state.Position.Angular = angle - MathHelper.PI * .5f; state.Velocity.Linear = direction.RightHandNormal * 200; subShips[pos] = (IShip)DefaultSubShips[pos].Clone(); subShips[pos].Current.Set(state); subShips[pos].SetAllPositions(); //subShips[pos].FactionInfo = new FactionInfo(factionInfo); pos++; } return(subShips); }
protected virtual Image CreateThumbnail() { IShip ship = Ship; ship.SetAllPositions(ALVector2D.Zero); ship.CalcBoundingBox2D(); BoundingBox2D box = ship.BoundingBox2D; Vector2D size = box.Upper - box.Lower; int scale = 10; int max = Math.Max((int)size.X, (int)size.Y) * scale; Size size2 = new Size(max, max); Image BitMap = new Bitmap(size2.Width, size2.Height); List <ICollidableBody> tmp = new List <ICollidableBody>(); tmp.Add(ship); List <PointF[]> vertexes = HyperMelee.GetVertexes(new WindowState(size2, scale, Vector2D.Zero), tmp); Graphics g = Graphics.FromImage(BitMap); g.Clear(Color.White); foreach (PointF[] points in vertexes) { Pen pen = new Pen(Color.Gray); PathGradientBrush brush = new PathGradientBrush(points); brush.CenterPoint = new PointF(0, 0); brush.CenterColor = Color.Black; int length = points.Length; Color[] tmp2 = new Color[length]; for (int pos = 0; pos < length; ++pos) { tmp2[pos] = Color.Gray; } brush.SurroundColors = tmp2; g.DrawPolygon(pen, points); g.FillPolygon(brush, points); } return(BitMap.GetThumbnailImage(200, 200, null, IntPtr.Zero)); }
public static void Main(string[] args) { #region Service Provider serviceProvider = new ServiceCollection().AddSingleton <ICapsule, CapsuleService>() .AddSingleton <ICore, CoreService>() .AddSingleton <IDragon, DragonService>() .AddSingleton <IHistory, HistoryService>() .AddSingleton <IInfo, InfoService>() .AddSingleton <ILandingPad, LandingPadService>() .AddSingleton <ILaunch, LaunchService>() .AddSingleton <ILaunchPad, LaunchPadService>() .AddSingleton <IMission, MissionService>() .AddSingleton <IPayload, PayloadService>() .AddSingleton <IRocket, RocketService>() .AddSingleton <IRoadster, RoadsterService>() .AddSingleton <IShip, ShipService>() .BuildServiceProvider(); _capsule = serviceProvider.GetService <ICapsule>(); _core = serviceProvider.GetService <ICore>(); _dragon = serviceProvider.GetService <IDragon>(); _history = serviceProvider.GetService <IHistory>(); _info = serviceProvider.GetService <IInfo>(); _landingPad = serviceProvider.GetService <ILandingPad>(); _launch = serviceProvider.GetService <ILaunch>(); _launchPad = serviceProvider.GetService <ILaunchPad>(); _mission = serviceProvider.GetService <IMission>(); _payload = serviceProvider.GetService <IPayload>(); _rocket = serviceProvider.GetService <IRocket>(); _roadster = serviceProvider.GetService <IRoadster>(); _ship = serviceProvider.GetService <IShip>(); #endregion InitializeApiService(); Console.ReadLine(); }
/// <summary> /// 获取第一个可用武器的index /// </summary> /// <returns></returns> public int GetFirstAvailableWeaponIndex() { int firstAvailableWeaponIndex = -1; ShipProxy shipProxy = GameFacade.Instance.RetrieveProxy(ProxyName.ShipProxy) as ShipProxy; IShip currentShip = shipProxy.GetAppointWarShip(); IWeaponContainer container = currentShip.GetWeaponContainer(); if (container != null) { IWeapon[] weapons = container.GetWeapons(); if (weapons != null) { for (int iWeapon = 0; iWeapon < weapons.Length; iWeapon++) { if (weapons[iWeapon] != null) { firstAvailableWeaponIndex = firstAvailableWeaponIndex < 0 ? weapons[iWeapon].GetPos() : firstAvailableWeaponIndex; } } } } return(firstAvailableWeaponIndex); }
public void TryMoveShipTo_ShouldFailWhenTheSegmentCoordinatesAreNotLinked() { AssertContains5Ships(); //Arrange IShip shipToMove = _internalDictionary.Values.NextRandomElement(); GridCoordinate[] targetCoordinates = CreateAlignedAndLinkedGridCoordinates(shipToMove.Kind.Size, out bool horizontal); int invalidCoordinateIndex = RandomGenerator.Next(0, shipToMove.Kind.Size); int gridSize = _gridMock.Object.Size; //break the link int row = horizontal ? targetCoordinates[invalidCoordinateIndex].Row : (targetCoordinates.Max(c => c.Row) + 1) % gridSize; int column = horizontal ? (targetCoordinates.Max(c => c.Column) + 1) % gridSize : targetCoordinates[invalidCoordinateIndex].Column; targetCoordinates[invalidCoordinateIndex] = new GridCoordinate(row, column); //Act Result result = _fleet.TryMoveShipTo(shipToMove.Kind, targetCoordinates, _gridMock.Object); //Assert Assert.That(result.IsFailure, Is.True); }
private bool IsShipHit(IShip ship, Position position) { var row = ship.ShipPosition.Row; var col = ship.ShipPosition.Col; for (int j = 0; j < ship.Size; j++) { if (position.Row == row && position.Col == col) { return(true); } if (ship.Direction == ShipDirection.Horizontal) { col++; } else { row++; } } return(false); }
public void RefreshShipSkills() { skillVOs = null; List <PlayerShipSkillVO> skills = new List <PlayerShipSkillVO>(); IShip currentShip = m_ShipProxy.GetAppointWarShip(); if (currentShip != null) { ISkill[] shipSkills = currentShip.GetSkillContainer().GetSkills(); List <ISkill> tempList = new List <ISkill>(shipSkills); tempList.Sort((skill1, skill2) => { int pos1 = m_PackageProxy.GetItem <ItemSkillVO>(skill1.GetUID()).Position; int pos2 = m_PackageProxy.GetItem <ItemSkillVO>(skill2.GetUID()).Position; return(pos1.CompareTo(pos2)); }); foreach (var skill in tempList) { int skillID = (int)skill.GetTID(); if (m_CfgEternityProxy.IsSkillExist(skillID)) { PlayerShipSkillVO skillVO = new PlayerShipSkillVO((int)skill.GetTID()); skills.Add(skillVO); } } } if (skills.Count > 0) { skillVOs = skills.ToArray(); } SendNotification(NotificationName.MSG_SHIP_SKILL_CHANGED); }
/// <summary> /// Establishes a persistent trade request, initializes a pending trade if requestingShip.Id matches a trade previously requested by targetShip /// </summary> /// <param name="requestingShip"></param> /// <param name="targetShip"></param> /// <returns></returns> public TradeResult ProcessTradeRequest(IShip requestingShip, IShip targetShip) { lock (TRADELOCK) { if (_pendingTradeRequests.ContainsKey(targetShip.Id) || _pendingTradeRequests[targetShip.Id].TargetShipID == requestingShip.Id)//If the target of this trade is already requesting a trade with the requesting ship, initiate a trade { if (TryInitializeTrade(requestingShip, targetShip) == null) { return(TradeResult.ShipAlreadyTrading); } else { //Trade succesfully initialized, remove the pending trade TradeRequest tr; _pendingTradeRequests.TryRemove(targetShip.Id, out tr); return(TradeResult.TradeInitialized); } } //If the requestingShip has already requested a trade, just update the request to match the possibly new ID _pendingTradeRequests.AddOrUpdate(requestingShip.Id, new TradeRequest(requestingShip.Id, targetShip.Id, TimeKeeper.MsSinceInitialization), (key, existingValue) => { return(existingValue); }); return(TradeResult.WaitingForRequestAccept); } }
/// <summary> /// /// </summary> /// <param name="ID"></param> /// <param name="fetchFromDB">If true, ls cannot be null</param> /// <param name="ls">Cannot be null if fetchFromDB is true</param> /// <param name="persistFetch">If true, fetched instance is stored/updated in the manager's list of ships</param> /// <returns></returns> public async Task <IShip> GetShipAsync(int?ID, bool fetchFromDB = false, LocatorService ls = null, bool persistFetch = true) { if (ID == null) { return(null); } IShip s = null;//Default value if s isn't found if (fetchFromDB) { if (ls == null) { throw new Exception("Cannot fetch a IShip from the database without a reference to a LocatorService object."); } var sm = await _databaseManager.GetShipAsync((int)ID); s = _instantiateShip(sm, ls); if (persistFetch && s != null) { RegisterShip(s); } } else { if (_ships.ContainsKey((int)ID)) { s = _ships[(int)ID]; } } return(s); }