/// <summary>
        /// Given any cell - calculate live neighbours
        /// </summary>
        /// <param name="x">X coord of Cell</param>
        /// <param name="y">Y coord of Cell</param>
        /// <returns>Number of live neighbours</returns>
        private int CalculateLiveNeighbours(int x, int y, CellStatus[,] currentGeneration)
        {
            var worldSize = currentGeneration.WorldSize();

            // Calculate live neighours
            int liveNeighbours = 0;

            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    if (x + i < 0 || x + i >= worldSize.Rows)   // Out of bounds
                    {
                        continue;
                    }
                    if (y + j < 0 || y + j >= worldSize.Columns)   // Out of bounds
                    {
                        continue;
                    }
                    if (x + i == x && y + j == y)       // Same Cell
                    {
                        continue;
                    }

                    // Add cells value to current live neighbour count
                    liveNeighbours += (int)currentGeneration[x + i, y + j];
                }
            }

            return(liveNeighbours);
        }
Beispiel #2
0
        internal static CellStatus[,] DestroyShip(CellStatus[,] enemyPlayerBoard, CellStatus[,] strategicOverlay, List <int[]> shipCoordinates)
        {
            int[] destroyCell = { -1, -1 };

            for (int index = 0; index < shipCoordinates.Count; index++)
            {
                destroyCell = shipCoordinates[index];

                for (int column = -1; column <= 1; column++)
                {
                    for (int row = -1; row <= 1; row++)
                    {
                        try
                        {
                            enemyPlayerBoard[destroyCell[0] + column, destroyCell[1] + row] = CellStatus.Blocked;
                            strategicOverlay[destroyCell[0] + column, destroyCell[1] + row] = CellStatus.Blocked;
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }

            return(strategicOverlay);
        }
Beispiel #3
0
        private static CellStatus[,] PlaceShips(CellStatus[,] board, List <int> shipCellNumber, int playerNumber)
        {
            List <List <int[]> > fakeList = new List <List <int[]> >();

            if (playerNumber == 1)
            {
                UI.BoardStatus(PlayerOneBoard, PlayerColor, fakeList, 1);
            }
            else
            {
                UI.BoardStatus(PlayerTwoBoard, PlayerColor, fakeList, 2);
            }

            Console.WriteLine("\n Place " + shipCellNumber[0] + " cell ship using starting coordinates and direction:\n");
            Console.Write(" ");
            string userInput = Console.ReadLine();

            Console.Clear();

            board = Ship.CreateShip(board, shipCellNumber, userInput, playerNumber);

            if (shipCellNumber.Count == 0 && playerNumber == 1)
            {
                PlayerOnePlacedAllShips = true;
            }
            if (shipCellNumber.Count == 0 && playerNumber == 2)
            {
                PlayerTwoPlacedAllShips = true;
            }

            return(board);
        }
Beispiel #4
0
    //  5   6   7
    //  3   P   4
    //  0   1   2
    void Relax(Vector2Int pos, ref int width, ref int height, CellStatus[,] cells)
    {
        //左右八个点
        Vector2Int cp   = pos;
        int        pIdx = CalculateIdx(ref cp);

        //0
        cp.x = pos.x - 1;
        cp.y = pos.y - 1;
        bool isBlock = IsBlock(new Vector2Int(pos.x - 1, pos.y), cells) || IsBlock(new Vector2Int(pos.x, pos.y - 1), cells);

        if (!isBlock)
        {
            Relax(pIdx, 14, cp, ref width, ref height, cells);
        }

        //1
        cp.x = pos.x;
        cp.y = pos.y - 1;
        Relax(pIdx, 10, cp, ref width, ref height, cells);

        //2
        cp.x    = pos.x + 1;
        cp.y    = pos.y - 1;
        isBlock = IsBlock(new Vector2Int(pos.x + 1, pos.y), cells) || IsBlock(new Vector2Int(pos.x, pos.y - 1), cells);
        if (!isBlock)
        {
            Relax(pIdx, 14, cp, ref width, ref height, cells);
        }

        //3
        cp.x = pos.x - 1;
        cp.y = pos.y;
        Relax(pIdx, 10, cp, ref width, ref height, cells);
        //4
        cp.x = pos.x + 1;
        cp.y = pos.y;
        Relax(pIdx, 10, cp, ref width, ref height, cells);

        //5
        cp.x    = pos.x - 1;
        cp.y    = pos.y + 1;
        isBlock = IsBlock(new Vector2Int(pos.x - 1, pos.y), cells) || IsBlock(new Vector2Int(pos.x, pos.y + 1), cells);
        if (!isBlock)
        {
            Relax(pIdx, 14, cp, ref width, ref height, cells);
        }
        //6
        cp.x = pos.x;
        cp.y = pos.y + 1;
        Relax(pIdx, 10, cp, ref width, ref height, cells);
        //7
        cp.x    = pos.x + 1;
        cp.y    = pos.y + 1;
        isBlock = IsBlock(new Vector2Int(pos.x + 1, pos.y), cells) || IsBlock(new Vector2Int(pos.x, pos.y + 1), cells);
        if (!isBlock)
        {
            Relax(pIdx, 14, cp, ref width, ref height, cells);
        }
    }
Beispiel #5
0
        private bool Move2(ref CellStatus[,] mat, ref int x, ref int y, ref Direction dir)
        {
            bool causedInfection = false;

            switch (mat[y, x])
            {
            case CellStatus.CLEAN:
                dir       = dir == Direction.UP ? Direction.LEFT : dir - 1;
                mat[y, x] = CellStatus.WEAKENED;
                break;

            case CellStatus.INFECTED:
                dir       = dir == Direction.LEFT ? Direction.UP : dir + 1;
                mat[y, x] = CellStatus.FLAGGED;
                break;

            case CellStatus.WEAKENED:
                mat[y, x]       = CellStatus.INFECTED;
                causedInfection = true;
                break;

            case CellStatus.FLAGGED:
                dir       = (Direction)(((int)dir + 2) % 4);
                mat[y, x] = CellStatus.CLEAN;
                break;
            }
            Continue(dir, ref x, ref y);
            return(causedInfection);
        }
Beispiel #6
0
 public Field(int width, int height)
 {
     this.Width  = width;
     this.Height = height;
     this.field  = new CellStatus[height, width];
     this.SetClear();
 }
Beispiel #7
0
        private static void WriteRowOfCells(CellStatus[,] board, int column, int row)
        {
            switch (board[column, row])
            {
            case CellStatus.Empty:
                Console.BackgroundColor = ConsoleColor.White;
                Console.Write("  ");
                break;

            case CellStatus.Occupied:
                Console.BackgroundColor = ConsoleColor.Red;
                Console.Write("  ");
                break;

            case CellStatus.Blocked:
                Console.Write("  ");
                break;

            case CellStatus.Hit:
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.Write("  ");
                break;

            case CellStatus.Fired:
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.Write("  ");
                break;
            }
            Console.BackgroundColor = ConsoleColor.Black;
        }
    private void ResetFloor()
    {
        floorCells = new CellStatus[numColumnsInFloor, numRowsInFloor];

        chunks = new Chunk[numChunksX, numChunksZ];

        partitionCount = 0;

        // Reset chunks
        for (int x = 0; x < numChunksX; x++)
        {
            for (int z = 0; z < numChunksZ; z++)
            {
                chunks[x, z]           = new Chunk(x, z, UnityEngine.Random.Range(numColumnsInChunk * x + 1, numColumnsInChunk * (x + 1) - 1), UnityEngine.Random.Range(numRowsInChunk * z + 1, numRowsInChunk * (z + 1) - 1));
                chunks[x, z].Partition = partitionCount;
                partitionCount++;
                chunks[x, z].CenterMarker = new GameObject();
                chunks[x, z].CenterMarker.transform.position = new Vector3((x * numColumnsInChunk) + (.5f * numColumnsInChunk), 2f, (z * numRowsInChunk) + (.5f * numRowsInChunk));
                chunks[x, z].CenterMarker.transform.parent   = chunkObjectsParent;
            }
        }

        // Reset Tiles
        for (int column = 0; column < numColumnsInFloor; column++)
        {
            for (int width = 0; width < numRowsInFloor; width++)
            {
                floorCells[column, width] = CellStatus.HasWall;
            }
        }
    }
Beispiel #9
0
        public void GetInfo(string gameId, string connectionId, string player)
        {
            if (games.ContainsKey(gameId))
            {
                MyGame      g         = games[gameId];
                Field       my        = null;
                List <Ship> deadShips = null;
                CellStatus[,] op = null;
                bool wait = true;

                if (g.Players[0].Name == player)
                {
                    g.Players[0].Id = connectionId;
                    my        = g.GetMap(0);
                    op        = g.GetCellStatus(1);
                    deadShips = g.GetDeadShips(1);
                    wait      = 1 == g.CurrentPlayer;
                }
                else if (g.Players[1].Name == player)
                {
                    g.Players[1].Id = connectionId;
                    my        = g.GetMap(1);
                    op        = g.GetCellStatus(0);
                    deadShips = g.GetDeadShips(0);
                    wait      = 0 == g.CurrentPlayer;
                }
                Clients.Client(connectionId).getInfo(my, op, deadShips, wait);
            }
            else
            {
                Clients.Caller.noGame();
            }
        }
Beispiel #10
0
        internal static void BoardStatus(CellStatus[,] board, ConsoleColor playerColor, List <List <int[]> > enemyShips, int playerNumber)
        {
            string player;
            string enemyShipsStatus = "";

            if (playerNumber == 1)
            {
                playerColor = ConsoleColor.Green;
                player      = "One";
            }
            else
            {
                playerColor = ConsoleColor.Cyan;
                player      = "Two";
            }

            if (enemyShips.Count != 0)
            {
                for (int i = 0; i < enemyShips.Count; i++)
                {
                    if (i == enemyShips.Count - 1)
                    {
                        enemyShipsStatus += enemyShips[i].Count.ToString();
                    }
                    else
                    {
                        enemyShipsStatus += enemyShips[i].Count.ToString() + ", ";
                    }
                }
            }
            else
            {
                enemyShipsStatus = "0";
            }

            Console.Write("\n [ ");
            Console.ForegroundColor = playerColor;
            Console.Write("Player " + player);
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(" ] --- Opponent ships remaining: " + enemyShipsStatus + "\n\n     ");
            Console.ForegroundColor = playerColor;
            Console.Write("1 2 3 4 5 6 7 8 9 10\n");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" ------------------------");

            for (int column = 0; column < 10; column++)
            {
                WriteLetter(column, playerColor);

                for (int row = 0; row < 10; row++)
                {
                    WriteRowOfCells(board, column, row);
                }

                WriteInstructions(column);

                Console.Write(Environment.NewLine);
            }
        }
 /// <summary>
 /// Initializes a new instance of the WorldMemento.
 /// </summary>
 public WorldMemento(int generationNumber, CellStatus[,] generation, WorldSize size, bool isAlive, int aliveCells)
 {
     GenerationNumber = generationNumber;
     Generation       = generation;
     IsAlive          = isAlive;
     AliveCells       = aliveCells;
     Size             = size;
 }
Beispiel #12
0
    private void Start()
    {
        Instance = this;

        FloorGenerator floorGen = GetComponent <FloorGenerator>();

        floorCells = floorGen.GenerateFloor();
    }
Beispiel #13
0
 /// <summary>
 /// Restores world's state
 /// </summary>
 public void RestoreState(WorldMemento memento)
 {
     Generation       = memento.Generation;
     GenerationNumber = memento.GenerationNumber;
     AliveCells       = memento.AliveCells;
     Size             = memento.Size;
     IsAlive          = memento.IsAlive;
 }
Beispiel #14
0
 public Map(int width, int height)
 {
     if (width < 1 || height < 1)
     {
         throw new InvalidMapSizeException();
     }
     Width         = width;
     Height        = height;
     CellsStatuses = new CellStatus[width, height];
 }
Beispiel #15
0
        /// <summary>
        /// Returns size of generation
        /// </summary>
        public static WorldSize WorldSize(this CellStatus[,] generation)
        {
            new List <int>().Count();

            return(new WorldSize
            {
                Rows = generation.GetUpperBound(0) + 1,
                Columns = generation.GetUpperBound(1) + 1,
            });
        }
Beispiel #16
0
        private static void ClickToContinue(CellStatus[,] board, int playerNumber, string message)
        {
            List <List <int[]> > fakeList = new List <List <int[]> >();

            UI.BoardStatus(board, PlayerColor, fakeList, playerNumber);
            Console.WriteLine("\n All ships has been placed. " + message);
            Console.Write(" ");
            Console.ReadKey();
            Console.Clear();
        }
Beispiel #17
0
 public void SetUnsafeMyField(int[,] field)
 {
     Field = new CellStatus[10, 10];
     for (int i = 0; i < 10; i++)
     {
         for (int j = 0; j < 10; j++)
         {
             Field[i, j] = (CellStatus)field[i, j];
         }
     }
 }
Beispiel #18
0
        internal static CellStatus[,] ModifyBoard(CellStatus[,] board, List <int> shipCellNumber, int[] coordinates, string direction, int playerNumber)
        {
            List <int[]> shipCoordinates = new List <int[]>();

            int[] cellCoordinates = { -1, -1 };

            for (int build = 0; build < shipCellNumber[0]; build++)
            {
                switch (direction)
                {
                case "up":
                    cellCoordinates = new int[] { coordinates[0] - build, coordinates[1] };
                    break;

                case "right":
                    cellCoordinates = new int[] { coordinates[0], coordinates[1] + build };
                    break;

                case "down":
                    cellCoordinates = new int[] { coordinates[0] + build, coordinates[1] };
                    break;

                case "left":
                    cellCoordinates = new int[] { coordinates[0], coordinates[1] - build };
                    break;
                }
                shipCoordinates.Add(cellCoordinates);
            }

            if (playerNumber == 1)
            {
                PlayerOneShipsPositions.Add(shipCoordinates);
            }
            else
            {
                PlayerTwoShipsPositions.Add(shipCoordinates);
            }

            bool shipCanBeBuild = Ship.CheckCellsAroundShip(board, shipCoordinates);

            if (shipCanBeBuild == true)
            {
                board = Ship.BuildShip(board, shipCoordinates);
                shipCellNumber.RemoveAt(0);

                return(board);
            }
            else
            {
                Console.WriteLine("\n Ship couldn't be build. It was either: near another ship, placed on another ship or out of board range.");

                return(board);
            }
        }
Beispiel #19
0
        public void NextGenerationTest(CellStatus[,] actual, CellStatus[,] expected, bool expectedIsAlive)
        {
            var            expectedAliveCells = expected.LifesCount();
            WorldGenerator worldGenerator     = new WorldGenerator();

            var nextGenerationResult = worldGenerator.NextGeneration(actual);

            Assert.Equal(expected, nextGenerationResult.Generation);
            Assert.Equal(expectedAliveCells, nextGenerationResult.AliveCells);
            Assert.Equal(expectedIsAlive, nextGenerationResult.IsGenerationAlive);
        }
Beispiel #20
0
        /// <summary>
        /// Advances the world to the next generation.
        /// </summary>
        public void NextGeneration()
        {
            var result = GenerationNumber == 0 ?
                         worldGenerator.RandomGeneration(Size) :
                         worldGenerator.NextGeneration(Generation);

            GenerationNumber++;
            AliveCells = result.AliveCells;
            Generation = result.Generation;
            IsAlive    = result.IsGenerationAlive;
        }
Beispiel #21
0
        internal static void StartBattleShips()
        {
            while (PlayerOnePlacedAllShips == false)
            {
                PlayerOneBoard = PlaceShips(PlayerOneBoard, PlayerTwoShips, 1);
            }
            ClickToContinue(PlayerOneBoard, 1, "Press anything to continue.\n");

            while (PlayerTwoPlacedAllShips == false)
            {
                PlayerTwoBoard = PlaceShips(PlayerTwoBoard, PlayerOneShips, 2);
            }
            ClickToContinue(PlayerTwoBoard, 2, "Press anything to start the game.\n");

            string playerNumber;

            while (Winner == false)
            {
                if (PlayerTurn == 1)
                {
                    PlayerTwoOverlay = BattleStatus(PlayerTwoBoard, PlayerTwoOverlay, PlayerTwoShipsPositions);
                    if (Winner == false)
                    {
                        PlayerTurn = 2;
                    }
                }
                else
                {
                    PlayerOneOverlay = BattleStatus(PlayerOneBoard, PlayerOneOverlay, PlayerOneShipsPositions);
                    if (Winner == false)
                    {
                        PlayerTurn = 1;
                    }
                }
            }

            if (PlayerTurn == 1)
            {
                playerNumber = "One";
            }
            else
            {
                playerNumber = "Two";
            }

            Console.Clear();
            Console.ForegroundColor = PlayerColor;
            Console.Write("\n Player " + playerNumber);
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" has WON the battle! Press anything to quit.\n");
            Console.Write(" ");
            Console.ReadKey();
        }
Beispiel #22
0
        internal static CellStatus[,] BuildShip(CellStatus[,] board, List <int[]> shipsCoordinates)
        {
            int[] coordinates = { -1, -1 };

            for (int i = 0; i < shipsCoordinates.Count; i++)
            {
                coordinates = shipsCoordinates[i];

                board[coordinates[0], coordinates[1]] = CellStatus.Occupied;
            }

            return(board);
        }
Beispiel #23
0
        private void PlaceInputInMatrix2(ref char[][] input, ref CellStatus[,] mat)
        {
            int m = input.Length;
            int p = (GRID_SIZE - m) / 2;

            for (int i = 0; i < m; ++i)
            {
                for (int j = 0; j < m; ++j)
                {
                    mat[i + p, j + p] = (input[i][j] == '#' ? CellStatus.INFECTED : CellStatus.CLEAN);
                }
            }
        }
Beispiel #24
0
    bool IsBlock(Vector2Int p1, CellStatus[,] cells)
    {
        if (p1.x < 0 || p1.x >= mMapWidth)
        {
            return(false);
        }
        if (p1.y < 0 || p1.y >= mMapHeight)
        {
            return(false);
        }

        return(cells[p1.x, p1.y] == CellStatus.Obstacle);
    }
Beispiel #25
0
        private static Level FindPath(Level level, CellStatus[,] statuses, int x, int y, bool random)
        {
            if (IsConnected(x, y, level.EndPositionX, level.EndPositionY))
            {
                return(level);
            }

            var availableDirections = GetAvailableDirections(level, statuses, x, y);

            if (ReachedDeadEnd(availableDirections))
            {
                return(null);
            }

            if (random)
            {
                availableDirections.Shuffle();
            }

            foreach (var direction in availableDirections)
            {
                // Make clones in order to explore this branch without side effects on the original Objects
                var clonedLevel    = (Level)level.Clone();
                var clonedStatuses = new CellStatus[level.Width, level.Height];
                Array.Copy(statuses, clonedStatuses, statuses.Length);

                // Set the destination Cell as Path
                var(destinationX, destinationY) = direction.NextPosition(x, y);
                clonedLevel.SetPathAt(destinationX, destinationY);
                clonedStatuses[destinationX, destinationY] = CellStatus.Unusable;

                // Set the other destinations as unusable
                foreach (var otherDirection in availableDirections.Where(dir => dir != direction))
                {
                    var(unusableX, unusableY)            = otherDirection.NextPosition(x, y);
                    clonedStatuses[unusableX, unusableY] = CellStatus.Unusable;
                }

                // Recursive call
                var path = FindPath(clonedLevel, clonedStatuses, destinationX, destinationY, random);
                // If path is not null means we have reached the end
                if (path != null)
                {
                    return(path);
                }
            }

            return(null);
        }
Beispiel #26
0
        public Desk(int fieldSize)
        {
            this.fieldSize = fieldSize;
            field          = new CellStatus[fieldSize, fieldSize];
            battleField    = new CellStatus[fieldSize, fieldSize];

            for (int i = 0; i < fieldSize; i++)
            {
                for (int j = 0; j < this.fieldSize; j++)
                {
                    battleField[i, j] = CellStatus.empty;
                }
            }
            enemyCnt = 0;
        }
Beispiel #27
0
        private static List <Direction> GetAvailableDirections(Level level, CellStatus[,] statuses, int originX, int originY)
        {
            var directions = new List <Direction>();

            foreach (var direction in (Direction[])Enum.GetValues(typeof(Direction)))
            {
                var(destinationX, destinationY) = direction.NextPosition(originX, originY);

                if (
                    Utils.IsInsideBoundaries(destinationX, destinationY, level.Width, level.Height) &&
                    statuses[destinationX, destinationY] == CellStatus.Usable)
                {
                    directions.Add(direction);
                }
            }
            return(directions);
        }
Beispiel #28
0
        internal static bool CheckCellsAroundShip(CellStatus[,] board, List <int[]> shipsCoordinates)
        {
            int[] coordinates = { -1, -1 };

            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    for (int k = 0; k < shipsCoordinates.Count; k++)
                    {
                        coordinates = shipsCoordinates[k];

                        try
                        {
                            if (board[coordinates[0] + i, coordinates[1] + j] != CellStatus.Empty)
                            {
                                return(false);
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }

            for (int i = 0; i < shipsCoordinates.Count; i++)
            {
                coordinates = shipsCoordinates[i];

                try
                {
                    board[coordinates[0], coordinates[1]] = CellStatus.Empty;
                }
                catch
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #29
0
        internal static CellStatus[,] CreateShip(CellStatus[,] board, List <int> shipCellNumber, string userInput, int playerNumber)
        {
            string direction = CheckInput.UserDirection(userInput);

            int[] coordinates = CheckInput.UserCoordinates(userInput);

            if (coordinates[0] == -1 || coordinates[1] == -1 || direction == null)
            {
                Console.WriteLine("\n Wrong input!\n");

                return(board);
            }
            else
            {
                board = GameEngine.ModifyBoard(board, shipCellNumber, coordinates, direction, playerNumber);

                return(board);
            }
        }
Beispiel #30
0
        internal static void CheckCellsStatus(CellStatus[,] enemyPlayerBoard)
        {
            int counter = 0;

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    if (enemyPlayerBoard[i, j] == CellStatus.Occupied)
                    {
                        counter++;
                    }
                }
            }

            if (counter == 0)
            {
                Winner = true;
            }
        }
Beispiel #31
0
 public Board()
 {
     cells = new CellStatus[nrows, ncols];
 }