コード例 #1
0
        private List <Weapon> GetShipWeapons(ShipType shipType)
        {
            List <Weapon> weapons = new List <Weapon>();

            string s = shipType.ToString().Substring(0,
                                                     shipType.ToString().Length - 4);

            foreach (var weapon in weaponTypes.Where(v => v.ToString().Contains(s)))
            {
                weapons.Add(weaponFactory.CreateWeapon(weapon));
            }

            return(weapons);
        }
コード例 #2
0
ファイル: Ship.cs プロジェクト: Isoldhe/Battleship
        }                                            // horizontal (H) or vertical (V)

        public Ship(ShipType shipType, int xLocation, int yLocation, Orientation orientation)
        {
            Name     = shipType.ToString();
            ShipType = shipType;
            switch (shipType)
            {
            case ShipType.Destroyer:
                Size = 2;
                break;

            case ShipType.AircraftCarrier:
                Size = 5;
                break;

            case ShipType.Submarine:
                Size = 4;
                break;

            case ShipType.Battleship:
            case ShipType.Cruiser:
                Size = 3;
                break;

            default:
                throw new ArgumentException($"Ship type [{shipType}] does not have a defined Size!", nameof(shipType));
            }
            XLocation   = xLocation;
            YLocation   = yLocation;
            Orientation = orientation;
        }
コード例 #3
0
ファイル: GameBoard.cs プロジェクト: chemass/Battleship
        /// <summary>
        /// Place a ship on the game board
        /// </summary>
        /// <param name="ship">Type of ship to place</param>
        /// <param name="cell">Starting cell</param>
        /// <param name="isHorizontal">Indicates if the ship is horizontal</param>
        public void PlaceShip(ShipType ship, Cell cell, bool isHorizontal)
        {
            if (_placedShips.HasFlag(ship))
            {
                throw new CannotPlaceException("This type of ship has already been placed.");
            }

            var shipLength = GetShipLength(ship);

            Cell[] targetRange = null;

            try
            {
                targetRange = cell.Range(shipLength, isHorizontal).ToArray();
            }
            catch (ArgumentOutOfRangeException ex)
            {
                throw new CannotPlaceException("Ship extends beyond board boundaries.", ex);
            }

            if (targetRange.Any(x => _board[x.ToBoardIndex()] != 0))
            {
                throw new CannotPlaceException("Ships may not overlap.");
            }

            foreach (var targetCell in targetRange)
            {
                _board[targetCell.ToBoardIndex()] = ship.ToString()[0];
            }

            _placedShips = _placedShips | ship;
        }
コード例 #4
0
        private string GetHullTypeString(ShipType shipType)
        {
            switch (shipType)
            {
            case ShipType.Scout:
                return("Scout");

            case ShipType.Fighter:
                return("Fighter");

            case ShipType.Interceptor:
                return("Interceptor");

            case ShipType.Bomber:
                return("Bomber");

            case ShipType.Gunship:
                return("Gunship");

            case ShipType.StealthFighter:
                return("Stealth Fighter");

            default:
                throw new NotSupportedException(shipType.ToString());
            }
        }
コード例 #5
0
        public GameObject CreateShip(ShipType shipType, Vector3 position)
        {
            if (!modelDict.ContainsKey(shipType))
            {
                throw new KeyNotFoundException($"No model for key ({shipType}) could be found");
            }

            var result = new GameObject(shipType.ToString());

            var collider = this.GetCollider(shipType);

            var rigidBody = new RigidBody();

            rigidBody.SetShapeFromCollider(collider);
            rigidBody.ClampAxis(Axis.Y);

            var script = this.GetBehaviour(shipType);

            var renderer = this.GetRenderer(shipType);

            result.AddComponent(collider);
            result.AddComponent(rigidBody);
            result.AddComponent(script);
            result.AddComponent(renderer);

            result.Transform.SetPosition(position.X, position.Y, position.Z);

            result.Initialise();

            return(result);
        }
コード例 #6
0
        /** <summary>A private helper method for reading in user specified starting coordinates.</summary>
         * <param name="type">The type of ship we are attempting to place.</param>
         * <param name="x">The column component of the coordinates.</param>
         * <param name="y">The row component of the coordinates.</param>
         * <param name="vertical">Flag to check if the ship should be placed vertically or not.</param>
         */
        private void ReadPlacementCoordinates(ShipType type, out uint x, out uint y, out bool vertical)
        {
            Displayln($"Where shall we position the {type.ToString()}, and should it be vertical?");
            Display("--> Enter position (A 0) and verticality (yes/no) (ex: A 0 yes): ");

            bool invalid;

            do
            {
                invalid = false;

                string input;
                ReadLine(out input);

                invalid = string.IsNullOrEmpty(input);

                string[] split_input = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                // Check that we got valid coordinates
                if (split_input.Length == 3)
                {
                    if (char.IsLetter(split_input[0], 0) &&
                        char.IsDigit(split_input[1], 0) &&
                        (split_input[2].ToLower() == "yes" || split_input[2].ToLower() == "no"))
                    {
                        x        = Convert.ToUInt32(char.ToUpper(Convert.ToChar(split_input[0])) - 'A');
                        y        = Convert.ToUInt32(split_input[1]);
                        vertical = split_input[2].ToLower() == "yes";
                        return;
                    }
                }

                invalid = true;

                // We failed to get our coordinates, let's go again.
                x        = y = 0;
                vertical = false;
                Displayln("\n<!> Please sir, use the coordinate system!\n");
                Displayln($"Where shall we position the {type.ToString()}?");
                Display("--> Enter position (ex: A 0): ");
            } while (invalid);
        }
コード例 #7
0
        static internal string GetShipNameOnce(ShipType shipType)
        {
            switch (shipType)
            {
            case ShipType.Fighter: return("Истребитель");

            case ShipType.Corvette: return("Корвет");

            default: return(shipType.ToString());
            }
        }
コード例 #8
0
ファイル: Output.cs プロジェクト: mark-russ/Battleship-2019
        /// <summary>
        /// Converts the given ship type into a string, trimming it so it will fit in a cell.
        /// </summary>
        /// <param name="shipType">The ship type enum to convert to string</param>
        /// <returns>A trimmed string matching the width of the board's cell.</returns>
        private static string GetShipShortName(ShipType shipType)
        {
            string shipName = shipType.ToString().ToUpper();

            if (shipName.Length <= cellWidth)
            {
                return(shipName.PadRight(cellWidth));
            }

            return(shipName.Substring(0, cellWidth));
        }
コード例 #9
0
    public string GetPartsList()
    {
        string partList = shipType.ToString() + " parts:\n\t";

        Transform[] trs = GetComponentsInChildren <Transform>();
        for (int i = 0; i < trs.Length; ++i)
        {
            partList += trs[i].gameObject.name + " ";
        }

        return(partList);
    }
コード例 #10
0
        public static int GetShipLength(ShipType shipType)
        {
            switch (shipType)
            {
            case ShipType.BattleShip:
                return(Constants.BattleshipLength);

            case ShipType.Destroyer:
                return(Constants.DestroyerLength);
            }

            throw new ArgumentException($"No length defined for ship type: {shipType.ToString()}.");
        }
コード例 #11
0
        public IShip CreateShip(ShipType shipType, IList <Weapon> weapons)
        {
            Type typeOfShip = Assembly.GetExecutingAssembly().GetTypes()
                              .FirstOrDefault(v => v.Name == shipType.ToString());

            IShip ship = (IShip)Activator.CreateInstance(typeOfShip, weapons);

            if (ship.Position == null)
            {
                ship.Position = (GenerateRandomShipPosition());
            }

            return(ship);
        }
コード例 #12
0
        // Создание префаба модульки корабля
        public static GameObject CreateShipModel(Transform AParent, SSHRace ARace, ShipType AShipType)
        {
            // Путь к каталогу префабов
            const string LPrefabPath      = "PL/Ship/";
            string       LPrefabShipName  = "/pfPLShip";
            string       LPrefabModelName = "";
            string       LRaceName        = ARace.ToString();

            // Выбор префаба на основе корабля
            if (AShipType == ShipType.Flagship)
            {
                LPrefabModelName = string.Concat(AShipType.ToString(), LPrefabShipName, AShipType.ToString());
            }
            else
            {
                LPrefabModelName = string.Concat(LRaceName, LPrefabShipName, AShipType.ToString(), LRaceName);
            }
            GameObject LModel = Create(LPrefabPath + LPrefabModelName, Vector3.zero);

            LModel.transform.SetParent(AParent, false);
            LModel.name = "Model";
            return(LModel);
        }
コード例 #13
0
        /// <summary>
        /// Validates and converts the supplied combination of parameters, and updates the internal state variables such as _map and _ships
        /// </summary>
        /// <param name="ship">The ShipType to be added to the map</param>
        /// <param name="alignment">Whether the ship is to be aligned vertically or horizontally</param>
        /// <param name="cellCoordinates">The location on the map of the bottom/left-most cell of the ship</param>
        public void AddShip(ShipType ship, Alignment alignment, string cellCoordinates)
        {
            if (ship == ShipType.None)
            {
                throw new Exception($"Cannot place a ShipType of None on the map using method Init");
            }

            if (_ships.Contains(ship))
            {
                throw new Exception($"{ship.ToString()} has already been placed on the map.");
            }

            // translate the user friendly coordinate to integer coordinates used to accessing the array representation of the map
            SplitCoordinates(cellCoordinates, out int xCoord, out int yCoord);

            // add the ship to the map and to the internal list of placed ships
            PlaceShipOnMap(ship, alignment, xCoord, yCoord);
            _ships.Add(ship);
        }
コード例 #14
0
        public void PlaceShipOnBoard(Player player)
        {
            bool IsPlaceBoardAuto = false;

            if (player.IsPC != true)
            {
                ControlOutput.ShowWhoseTurn(player);
                IsPlaceBoardAuto = ControlInput.IsPlaceBoardAuto();
                if (!IsPlaceBoardAuto)
                {
                    Console.WriteLine("Input the location and direction(l, r, u, d) of the ships. Ex:) a2, r:");
                }
            }
            for (ShipType s = ShipType.Destroyer; s <= ShipType.Carrier; s++)
            {
                PlaceShipRequest ShipToPlace = new PlaceShipRequest();
                ShipPlacement    result;
                do
                {
                    if (!player.IsPC && !IsPlaceBoardAuto)
                    {
                        ShipToPlace          = ControlInput.GetLocationFromUser(s.ToString());
                        ShipToPlace.ShipType = s;
                        result = player.PlayerBoard.PlaceShip(ShipToPlace);
                        if (result == ShipPlacement.NotEnoughSpace)
                        {
                            Console.WriteLine("Not Enough Space!");
                        }
                        else if (result == ShipPlacement.Overlap)
                        {
                            Console.WriteLine("Overlap placement!");
                        }
                    }
                    else
                    {
                        ShipToPlace          = ControlInput.GetLocationFromComputer();
                        ShipToPlace.ShipType = s;
                        result = player.PlayerBoard.PlaceShip(ShipToPlace);
                    }
                } while (result != ShipPlacement.Ok);
            }
        }
コード例 #15
0
        public void PlaceShipOnBoard(Player player)
        {
            bool IfManuallyPlaceTheShips = false;

            if (player.IsPC != true)
            {
                IfManuallyPlaceTheShips = Inputs.IfManuallyPlaceTheShips();
                if (!IfManuallyPlaceTheShips)
                {
                    Console.WriteLine("Input the location and direction(L, R, U, D) of the ships. Ex:) A6, L:");
                }
            }
            for (ShipType s = ShipType.Destroyer; s <= ShipType.Carrier; s++)
            {
                ShipCoordinates ShipToPlace = new ShipCoordinates();
                ShipPlacements  result;
                do
                {
                    if (!player.IsPC && !IfManuallyPlaceTheShips)
                    {
                        ShipToPlace          = Inputs.GetCoordinatesForPlayer1(s.ToString());
                        ShipToPlace.ShipType = s;
                        result = player.PlayerBoard.PlaceShip(ShipToPlace);
                        if (result == ShipPlacements.NotEnoughSpace)
                        {
                            Console.WriteLine("Not Enough Space!");
                        }
                        else if (result == ShipPlacements.Overlap)
                        {
                            Console.WriteLine("Overlap placement!");
                        }
                    }
                    else
                    {
                        ShipToPlace          = Inputs.GetLocationFromComputer();
                        ShipToPlace.ShipType = s;
                        result = player.PlayerBoard.PlaceShip(ShipToPlace);
                    }
                } while (result != ShipPlacements.Ok);
            }
        }
コード例 #16
0
        public static int Size(ShipType ship)
        {
            switch (ship)
            {
            case ShipType.Battleship:
                return(4);

            case ShipType.Carrier:
                return(5);

            case ShipType.Cruiser:
                return(3);

            case ShipType.Destroyer:
                return(2);

            case ShipType.Submarine:
                return(3);

            default:
                throw new ArgumentOutOfRangeException(nameof(ship), ship.ToString() + " is not a valid type of ship");
            }
        }
コード例 #17
0
ファイル: MonoHangar.cs プロジェクト: Avatarchik/EmpireClient
 // Смена типа или количества кораблика
 public void Change(ShipType AShipType, int ACount)
 {
     FSelf.Count = ACount;
     // Обновление строчки количества
     _TextCount.text = SSHLocale.CountToShortString(ACount);
     // Тип кораблика не изменился
     if (AShipType == FSelf.ShipType)
     {
         return;
     }
     // Меняем тип кораблика
     FSelf.ShipType = AShipType;
     if (FPrefab != null)
     {
         Destroy(FPrefab.gameObject);
     }
     // Для нового кораблика задаем спрайт
     if (AShipType != ShipType.Empty)
     {
         FPrefab        = PrefabManager.CreateShipModel(_PanelModel, Engine.Player.Race, AShipType).transform;
         _TextType.text = AShipType.ToString();
         _PanelInfo.SetActive(true);
         if (IsFocused)
         {
             CheckEnterAny();
         }
     }
     // Для пустого слота выключаем кнопку
     else
     {
         _PanelInfo.SetActive(false);
         if (IsFocused)
         {
             Deactivate();
         }
     }
 }
コード例 #18
0
 public void SetLocalizedName(ShipType type, string value)
 {
     Set(nameof(ShipType), type.ToString(), value);
 }
コード例 #19
0
 public string GetLocalizedName(ShipType type)
 {
     return(Get(nameof(ShipType), type.ToString()));
 }
コード例 #20
0
 public IBattleship GetBattleship(ShipType shipType)
 {
     return(_serviceLocator.Resolve <IBattleship>(shipType.ToString()));
 }
コード例 #21
0
ファイル: GridService.cs プロジェクト: jdwaudby/battleship
        public bool HasShipBeenSunk(Grid grid, ShipType shipType)
        {
            var status = (SquareStatus)Enum.Parse(typeof(SquareStatus), shipType.ToString());

            return(!GetPositions(grid, status).Any());
        }
コード例 #22
0
 public override string ToString()
 {
     return(Type.ToString() + ": " + (Duration / 1000.0f).ToString("0.0"));
 }
コード例 #23
0
 public Ship(ShipType type)
 {
     GO = Resources.Load("Ship/" + type.ToString()) as GameObject;
 }
コード例 #24
0
ファイル: GameBoard.cs プロジェクト: chemass/Battleship
        private bool IsDestroyed(ShipType ship, Cell targetCell)
        {
            var c = ship.ToString()[0];

            return(!_board.Any(x => x == c));
        }
コード例 #25
0
ファイル: Ship.cs プロジェクト: AdmiralPotato/ggj2013
 public static Ship Create(ShipType type, Vector3? position = null)
 {
     Ship result;
     switch (type)
     {
         case ShipType.Spearhead:
             result = new Ship(2000, position) { MaxShields = 500, Tubes = 2, PhaserBanks = 1, RepairCrews = 3 };
             result.BeamWeapons.AddRange((BeamType[])Enum.GetValues(typeof(BeamType)));
             result.BeamWeapons.Remove(BeamType.ShadowTether);
             result.Projectiles[ProjectileType.Torpedo] = 10;
             result.Projectiles[ProjectileType.Nuke] = 1;
             result.Projectiles[ProjectileType.Hardshell] = 1;
             result.Projectiles[ProjectileType.Knockshot] = 1;
             result.Projectiles[ProjectileType.Skattershot] = 1;
             break;
         case ShipType.Skirmisher:
             result = new Ship(2000, position) { MaxShields = 500, Tubes = 2, PhaserBanks = 2, RepairCrews = 3 };
             result.BeamWeapons.AddRange((BeamType[])Enum.GetValues(typeof(BeamType)));
             result.BeamWeapons.Remove(BeamType.ShadowTether);
             result.Projectiles[ProjectileType.Torpedo] = 10;
             break;
         case ShipType.Beserker:
             result = new Ship(5000, position) { MaxShields = 0, Tubes = 0, PhaserBanks = 1, MaximumForce = 12500, RepairCrews = 3 };
             result.BeamWeapons.Add(BeamType.HullPiercing);
             result.BeamWeapons.Add(BeamType.SelfDestruct);
             result.BeamWeapons.Add(BeamType.PlasmaVent);
             break;
         case ShipType.Gunboat:
             result = new Ship(1500, position) { MaxShields = 600, Tubes = 4, PhaserBanks = 1, RepairCrews = 3 };
             result.BeamWeapons.Add(BeamType.SuppresionPulse);
             result.BeamWeapons.Add(BeamType.ShadowTether);
             result.Projectiles[ProjectileType.Torpedo] = 10;
             result.Projectiles[ProjectileType.Nuke] = 1;
             result.Projectiles[ProjectileType.Hardshell] = 1;
             break;
         case ShipType.Capital:
             result = new Ship(3000, position) { MaxShields = 1000, Tubes = 5, RepairCrews = 3 };
             result.BeamWeapons.Add(BeamType.StandardPhaser);
             result.BeamWeapons.Add(BeamType.ShieldDampener);
             result.BeamWeapons.Add(BeamType.ShadowTether);
             result.Projectiles[ProjectileType.Torpedo] = 10;
             result.Projectiles[ProjectileType.Nuke] = 1;
             result.Projectiles[ProjectileType.Hardshell] = 1;
             break;
         default:
             throw new NotImplementedException("Unknown ship type " + type.ToString());
     }
     return result;
 }
コード例 #26
0
 public IBaseShip Get(string name)
 {
     return(_shipType switch
     {
         ShipType.Battleship => new BattleShip(name),
         ShipType.Destroyer => new DestroyerShip(name),
         _ => throw new InvalidOperationException(Constants.InvalidShipTypeException(_shipType.ToString())),
     });