Beispiel #1
0
 /// <summary>
 /// Simulates infection of a neighboring LivingUnit. Only LivingUnits to the left, right,
 /// top, and bottom of the Virus. Only infects a single neighbor.
 /// </summary>
 /// <param name="grid">The grid of Units.</param>
 private void Infect(Unit[,] grid)
 {
     // Iterate through each of the directions (left, right, top, bottom)
     foreach (var dir in GridHelper.directions)
     {
         // Calculate the row and column of the neighbor
         int newRow = Location.r + dir.Item1;
         int newCol = Location.c + dir.Item2;
         // Check if the neighbor is within the grid
         if (!grid.InGridBounds(newRow, newCol))
         {
             // Try a different direction
             continue;
         }
         // Otherwise, get the neighbor
         Unit neighbor = grid[newRow, newCol];
         // Check if there is a non-null LivingUnit in the block
         // Infects a unit even if it is already infected
         if (neighbor != null && neighbor is LivingUnit)
         {
             // Infect the neighbor
             (neighbor as LivingUnit).BeInfected();
             // Do not infect any other neighbors
             break;
         }
     }
 }
Beispiel #2
0
        public GamePlay(ContentManager contentManager)
        {
            //cManager.RootDirectory = "Content";
            //Console.WriteLine("Content Manager root directory: "+cManager.RootDirectory.ToString());
            //paddle = cManager.Load<Texture2D>(cManager.RootDirectory+"/GameAssets/breakout_paddle");
            //entityList = new List<Entities.BaseEntity>();

            currentKeyboardState = Keyboard.GetState();
            previousKeyboardState = currentKeyboardState;

            currentMouseState = Mouse.GetState();
            previousMouseState = Mouse.GetState();

            RoughnessPosition = new Vector2();
            RoughnessPosition.X = 100;
            RoughnessPosition.Y = 20;

            WaterTexture = contentManager.Load<Texture2D>("res/art/terrain/water_block");
            GrassTexture = contentManager.Load<Texture2D>("res/art/terrain/grass_block");
            MountainTexture = contentManager.Load<Texture2D>("res/art/terrain/mountain_block");
            kootenayFont = contentManager.Load<SpriteFont>("res/fonts/kootenay");

            _terrain = new Terrain("res/art/terrain/grass_block", _boxWidth, _boxHeight,
                Game1._DEFAULT_SCREEN_WIDTH, Game1._DEFAULT_SCREEN_HEIGHT, GrassTexture, WaterTexture, MountainTexture);
            _terrain.GenerateNewMap();

            _unitMap = new Unit[_terrain.ArrayWidth, _terrain.ArrayHeight];
            GenerateNewUnitMap();

            LoadContent(contentManager);
        }
Beispiel #3
0
    public void Create(FightCtllerView ctl, FightGrid grid)
    {
        m_ctller = ctl;
        m_fight_grid = grid;

        Vector2 min = new Vector2(float.MaxValue, float.MaxValue);
        Vector2 max = new Vector2(float.MinValue, float.MinValue);

        m_units = new Unit[FightGrid.UnitCount.Y, FightGrid.UnitCount.X];
        for (int y = 0; y < FightGrid.UnitCount.Y; ++y)
        {
            for (int x = 0; x < FightGrid.UnitCount.X; ++x)
            {
                GameObject obj_unit = ResMgr.Instance.CreateGameObject("Fight/GridUnit", gameObject);
                obj_unit.transform.localPosition = grid.Units[y, x].Position * Launcher.SpriteScale;
                FightGridUnitView uv = obj_unit.GetComponent<FightGridUnitView>();
                uv.Create(this, grid.Units[y, x]);
                m_units[y, x] = new Unit(new Int2D(x, y), uv);

                min.x = Mathf.Min(min.x, grid.Units[y, x].Position.x - FightGrid.UnitSize / 2);
                min.y = Mathf.Min(min.y, grid.Units[y, x].Position.y - FightGrid.UnitSize / 2);

                max.x = Mathf.Max(max.x, grid.Units[y, x].Position.x + FightGrid.UnitSize / 2);
                max.y = Mathf.Max(max.y, grid.Units[y, x].Position.y + FightGrid.UnitSize / 2);
            }
        }
        min *= Launcher.SpriteScale;
        max *= Launcher.SpriteScale;
        BoxCollider cld = gameObject.AddComponent<BoxCollider>();
        cld.center = min + (max - min) / 2;
        cld.size = (max - min);

        m_fight_grid.OnAddCreature += OnAddCreature;
    }
Beispiel #4
0
        public GamePlay(ContentManager contentManager)
        {
            //cManager.RootDirectory = "Content";
            //Console.WriteLine("Content Manager root directory: "+cManager.RootDirectory.ToString());
            //paddle = cManager.Load<Texture2D>(cManager.RootDirectory+"/GameAssets/breakout_paddle");
            //entityList = new List<Entities.BaseEntity>();

            currentKeyboardState  = Keyboard.GetState();
            previousKeyboardState = currentKeyboardState;

            currentMouseState  = Mouse.GetState();
            previousMouseState = Mouse.GetState();

            RoughnessPosition   = new Vector2();
            RoughnessPosition.X = 100;
            RoughnessPosition.Y = 20;

            WaterTexture    = contentManager.Load <Texture2D>("res/art/terrain/water_block");
            GrassTexture    = contentManager.Load <Texture2D>("res/art/terrain/grass_block");
            MountainTexture = contentManager.Load <Texture2D>("res/art/terrain/mountain_block");
            kootenayFont    = contentManager.Load <SpriteFont>("res/fonts/kootenay");

            _terrain = new Terrain("res/art/terrain/grass_block", _boxWidth, _boxHeight,
                                   Game1._DEFAULT_SCREEN_WIDTH, Game1._DEFAULT_SCREEN_HEIGHT, GrassTexture, WaterTexture, MountainTexture);
            _terrain.GenerateNewMap();

            _unitMap = new Unit[_terrain.ArrayWidth, _terrain.ArrayHeight];
            GenerateNewUnitMap();

            LoadContent(contentManager);
        }
Beispiel #5
0
 public PlayerControlManager(int xSize, int ySize, Unit[,] units, Explosive[,] explosions)
 {
     this.xSize      = xSize;
     this.ySize      = ySize;
     this.units      = units;
     this.explosions = explosions;
 }
Beispiel #6
0
    TileObject[,] tiles;  //change to basetile?

    void Awake()
    {
        int gridSize = GameObject.Find("Managers").GetComponent <GridManager>().gridSize;

        tiles = new TileObject[gridSize, gridSize];
        units = new Unit[gridSize, gridSize];
    }
Beispiel #7
0
    public static void update_OneUnitCoord_onTable(Unit u, Unit[,] table)
    {
        int coordX = u.CurrentColumn;
        int coordY = u.CurrentRow;

        table [coordX, coordY] = u;
    }
Beispiel #8
0
 private void ChangeInVariation(Variation variation, Unit[,] newFillArray, bool state)
 {
     foreach (var item in variation.VariationPoints)
     {
         newFillArray[(int)item.X, (int)item.Y].IsInVariation = state;
     }
 }
Beispiel #9
0
 public Navigator(World world)
 {
     _world          = world;
     _map            = new Unit[world.Size.X, world.Size.Y];
     _foodMap        = new FoodItem[world.Size.X, world.Size.Y];
     _individualsMap = new Individual[world.Size.X, world.Size.Y];
 }
Beispiel #10
0
        public void InitializeGridFromLocalData(int sideLength)
        {
            SideLength         = sideLength;
            Rows               = Columns = SideLength;
            Units              = GetNewEmptyGrid();
            UnitCounter        = 0;
            Data.MaxValue      = SideLength - 1;
            Data.CurrentLayout = Data.layouts[SideLength];
            Data.Score         = GameManager.CurrentLocalData.LastScores[SideLength - 3];
            State              = GridState.Game;
            CanUndo            = false;

            CreateUnitsFromState(GameManager.CurrentLocalData.GridState[SideLength - 3]);
            LastUnitsState     = new int[Rows, Columns];
            LastLastUnitsState = new int[Rows, Columns];

            drawer.SetGridImageBySize(SideLength);

            Wait.ForFrames(Drawer.TimingsConfig.framesBeforeDrawingUnits, () =>
            {
                StartCoroutine(DrawUnitsWithDelay());
            });

            GameManager.UpdateScoreText();
        }
        //Атака компьютера по человеку
        public static Point AutoAttack(ref Unit[,] matrix_state)
        {
            Random rnd = new Random();
            Point  tmp = new Point(0, 0); // создаем темповую точку, для того, чтобы менять ее, если вдруг точка не пустая
            int    x = 0, y = 0;          // Координаты x,y для матрицы
            bool   flag = true;           // Для вызода из цикла

            while (flag)                  //Не выходим изцикла пока что не найдем точку с морем
            {
                x = rnd.Next(0, 10);
                Thread.Sleep(10);//Задержка, чтобы рандом был рандомным
                y = rnd.Next(0, 10);

                if (matrix_state[x, y].Get_Unit_Type() == unit_type.sea) //Сравниваем тип ячейки входной матрицы с типом моря
                                                                         //И если всё хорошо, то выходим из цикла и в темповую переменную кидаем эту точку
                {
                    flag = false;
                    tmp  = new Point(x, y);
                    matrix_state[x, y].Set_Unit_Type(unit_type.hit_sea);
                }
            }

            Point result = tmp;

            return(result);
        }
Beispiel #12
0
        /// <summary>
        /// Computes the state of a given "block" in the grid in the new generation
        /// given the grid and the block.
        /// </summary>
        /// <remarks>
        /// Uses row and column instead of Unit since the focus is on
        /// the location of the Unit, not its parameters.
        /// </remarks>
        /// <param name="grid">The grid in which the block to compute is.</param>
        /// <param name="row">The row (within the grid) of the block to update.</param>
        /// <param name="col">The column (within the grid) of the block to update.</param>
        /// <returns>The new Unit that should occupy the block in this new generation. Null if no unit
        /// should occupy the block.</returns>
        public static Unit NewBlockState(Unit[,] grid, int row, int col)
        {
            // The current Unit in the block to update
            Unit thisUnit = grid[row, col];

            int allNeighbors = CountAllNeighbors(grid, row, col);

            // Check if the current block is empty
            if (thisUnit == null)
            {
                // Check if a new unit should be born (which happens only
                // if the block has exactly 3 neighbours)
                if (allNeighbors == OVER_POP)
                {
                    // Birth the new unit
                    return(NewbornUnit(grid, row, col));
                }
            }

            // Check if the Unit is a Virus
            if (!(thisUnit is LivingUnit))
            {
                // Update the Virus with separate Virus-oriented computations
                return(NewVirusState(grid, row, col));
            }
            // Otherwise, the Unit is a living unit
            else
            {
                // Update the LivingUnit with separate LivingUnit-oriented computations
                return(NewLivingState(grid, row, col));
            }
        }
Beispiel #13
0
        /// <summary>
        /// Returns the number of non-null Unit neighbors, either all Virus or all LivingUnit,
        /// of the block at (row, col).
        /// </summary>
        /// <remarks>
        /// Reusable method for both Virus counting and LivingUnit counting.
        /// </remarks>
        /// <param name="grid">Grid to use for counting neighbors.</param>
        /// <param name="row">Row (within the grid) of the block whose neighbors are counted.</param>
        /// <param name="col">Column (within the grid) of the block whose neighbors are counted.</param>
        /// <param name="countViral">Whether to count Viruses as neighbors (in which case LivingUnit
        /// neighbors are not counted), or not count them as neighbors (in which case only LivingUnit
        /// neighbors are counted).</param>
        /// <returns>The number of non-null Virus neighbors if "countViral" is true, or the number
        /// of non-null LivingUnit neighbors if "countViral" is false. Neighbors are in the Moore neighborhood.</returns>
        private static int NumberOfNeighbors(Unit[,] grid, int row, int col, bool countViral)
        {
            // Will store the number of neighbors
            int neighbors = 0;

            // Iterate through the Moore neighborhood
            // Iterate row by row, starting from the row above the block and ending at the row
            // below the block.
            for (int i = row - 1; i <= row + 1; i++)
            {
                // Iterate column by column, starting from the column to the left of the block
                // and ending at the column to the right of the block.
                for (int j = col - 1; j <= col + 1; j++)
                {
                    // Check if the current block is not the original block at (row, col),
                    // that it is inside the grid bounds, and that the Unit stored in the block is not null
                    if ((i != row || j != col) && grid.InGridBounds(i, j) && grid[i, j] != null)
                    {
                        // Count the current neighbor only if Viruses should be counted and the neighbor is
                        // not a LivingUnit, or if Viruses should not be counted and the neighbour is a LivingUnit
                        neighbors += (!countViral == grid[i, j] is LivingUnit ? 1 : 0);
                    }
                }
            }
            // Return the number of neighbors corresponding to the criterion of Virus counting or not counting
            return(neighbors);
        }
Beispiel #14
0
        /// <summary>
        /// Gets a list of all the non-null Unit neighbors of a block in the grid.
        /// </summary>
        /// <param name="grid">Grid to use for finding neighbors.</param>
        /// <param name="row">Row (within the grid) of the block whose neighbors are found.</param>
        /// <param name="col">Column (within the grid) of the block whose neighbors are found.</param>
        /// <returns>A List of non-null Units which are neighbors of the block at (row, col).</returns>
        private static List <Unit> GetAllNeighbors(Unit[,] grid, int row, int col)
        {
            // List that will store all the neighbors
            List <Unit> neighbors = new List <Unit>();

            // Iterate through the Moore neighborhood
            // Iterate row by row, starting from the row above the block and ending at the row
            // below the block.
            for (int i = row - 1; i <= row + 1; i++)
            {
                // Iterate column by column, starting from the column to the left of the block
                // and ending at the column to the right of the block.
                for (int j = col - 1; j <= col + 1; j++)
                {
                    // Check if the current block is not the original block at (row, col),
                    // that it is inside the grid bounds, and that the Unit stored in the block is not null
                    if ((i != row || j != col) && grid.InGridBounds(i, j) && grid[i, j] != null)
                    {
                        // Store this neighbor
                        neighbors.Add(grid[i, j]);
                    }
                }
            }
            // Return all the neighbors
            return(neighbors);
        }
Beispiel #15
0
        public Terrain()
        {
            MapWidth   = Config.GetInstance().iMapDefaultWidth - 1;
            MapHeight  = Config.GetInstance().iMapDefaultHeight - 1;
            MinHeight  = Config.GetInstance().minheight;
            MaxHeight  = Config.GetInstance().maxheight;
            Map        = new double[HeightMapWidth, HeightMapHeight];
            FeatureMap = new Unit[MapWidth, MapHeight];

            InitMap(MinHeight);
            LogFile.GetInstance().WriteLine("HeightMap() " + HeightMapWidth + " " + HeightMapHeight);

            texturestages = new List <MapTextureStage>();
            texturestages.Add(new MapTextureStage());

            //texturestages = Sm3Persistence.GetInstance().LoadTextureStages(TdfParser.FromFile("maps/Whakamatunga_Riri.sm3").RootSection.SubSection("map/terrain"));
            //Sm3Persistence.GetInstance().LoadHeightMap(TdfParser.FromFile("maps/Whakamatunga_Riri.sm3").RootSection.SubSection("map/terrain"));

            renderableheightmap   = new RenderableHeightMap(this, Map, SquareSize, SquareSize, texturestages);
            renderableallfeatures = new RenderableAllFeatures(this);
            // water must be last, otherwise you cant see through it ;-)
            renderablewater = new RenderableWater(new Vector3(), new Vector2(HeightMapWidth * SquareSize, HeightMapHeight * SquareSize));
            // minimap last, covers everything else
            renderableminimap = new RenderableMinimap(this, renderableheightmap);

            //OnTerrainModified();
        }
Beispiel #16
0
        /// <summary>
        /// Gets the number of neighbors of the same type as this Multicellular
        /// in a 5x5 square centered on the organism.
        /// </summary>
        /// <param name="grid"></param>
        /// <returns> an integer representing the number of neighbours of the same species that this unit has </returns>
        protected int NumberOfSameSpeciesNeighbors(Unit[,] grid)
        {
            // Create a counter to store the number of same species neighbours
            int numNeighbors = 0;
            // Compute the boundaries of the area to check for same species neighbours
            int rowLowerBound = Math.Max(0, Location.r - EXTENDED_NEIGHBORHOOD_SIZE / 2),
                colLowerBound = Math.Max(0, Location.c - EXTENDED_NEIGHBORHOOD_SIZE / 2);
            int rowUpperBound = Math.Min(grid.GetLength(GridHelper.ROW), Location.r + EXTENDED_NEIGHBORHOOD_SIZE / 2 + 1),
                colUpperBound = Math.Min(grid.GetLength(GridHelper.COLUMN), Location.c + EXTENDED_NEIGHBORHOOD_SIZE / 2 + 1);

            // Loop through all rows in the area to be checked to check each grid cell
            for (int i = rowLowerBound; i < rowUpperBound; i++)
            {
                // Loop through all columns in the area to be checked to check each grid cell
                for (int j = colLowerBound; j < colUpperBound; j++)
                {
                    // Check if the current grid cell is in the grid and holds a unit
                    if (grid.InGridBounds(i, j) && grid[i, j] != null)
                    {
                        // Increase the number of same species neighbour in the community
                        // only if the type of the unit in the current grid cell matches the type of the current unit
                        numNeighbors += grid[i, j].GetType() == this.GetType() ? 1 : 0;
                    }
                }
            }
            // Return the number of same species neighbours in the area surrounding this unit
            return(numNeighbors);
        }
Beispiel #17
0
 public Grid(int cellsNum, int cellSize)
 {
     CellsNum = cellsNum;
     CellSize = cellSize;
     _cells   = new Unit[CellsNum, CellsNum];
     Clear();
 }
Beispiel #18
0
    public Grid(int dimension)
    {
        int result = dimension * dimension;

        wholeGrid      = new Unit[result, result];
        this.dimension = dimension;
    }
Beispiel #19
0
        /// <summary>
        /// Calculate the score of the current grid, adding it to the state's cumulative score
        /// and checking if the game is over
        /// </summary>
        /// <returns> The score of the current grid in the simulation </returns>
        public int CalculateScore()
        {
            // get the current grid of units in the simulation
            Unit[,] grid = currentState.UnitGrid;
            //keeps track of the board's current score
            int gridScore = 0;

            //loop through the entire grid
            for (int j = 0; j < grid.GetLength(GridHelper.ROW); j++)
            {
                for (int k = 0; k < grid.GetLength(GridHelper.COLUMN); k++)
                {
                    //check if block is a virus or not a cell - if so, add the block's species complexity to the total
                    if (!(grid[j, k] is Virus) && grid[j, k] != null)
                    {
                        //add the product of the unit's species complexity and age, or just the species complexity if they are new, to the grid score
                        gridScore += Math.Max((grid[j, k] as LivingUnit).SpeciesComplexity * (grid[j, k] as LivingUnit).Age, (grid[j, k] as LivingUnit).SpeciesComplexity);
                    }
                }
            }
            // if the current score of the board is higher than the highest recorded concurrent score, it becomes the new highest concurrent score
            if (gridScore > HighestConcurrentScore)
            {
                HighestConcurrentScore = gridScore;
            }
            // add the score of the board to the tracker of the current board's score
            CurrentScore += gridScore;
            return(gridScore);
        }
Beispiel #20
0
    /// <summary>
    /// Start a new game, refresh all the data
    /// </summary>
    public void NewGame()
    {
        ClearGame();
        boardUnit  = new Unit[BoardInfo.Row, BoardInfo.Col];
        boardBread = new Unit[BoardInfo.Row, BoardInfo.Col];
        boardState = new GridState[BoardInfo.Row, BoardInfo.Col];
        playerInfo = new Dictionary <Unit.TypeEnum, int>[2] {
            new Dictionary <Unit.TypeEnum, int>(), new Dictionary <Unit.TypeEnum, int>()
        };

        for (int r = 0; r < BoardInfo.Row; r++)
        {
            for (int c = 0; c < BoardInfo.Col; c++)
            {
                boardState[r, c] = GridState.Void;
            }
        }

        boardState[BoardInfo.Base[0].R, BoardInfo.Base[0].C] = GridState.Base0;
        boardState[BoardInfo.Base[1].R, BoardInfo.Base[1].C] = GridState.Base1;

        foreach (Position pos in BoardInfo.BreadList)
        {
            CreateUnit(new UnitInfo(pos, Unit.TypeEnum.Bread));
        }
        restBreadNum = BoardInfo.BreadList.Length;

        foreach (UnitInfo info in BoardInfo.InitUnitList)
        {
            CreateUnit(info);
        }
    }
Beispiel #21
0
        /// <summary>
        /// Splits up the Colony into 4 cells in a 2x2 square. Called when there is insufficient
        /// food for the Colony.
        /// </summary>
        /// <remarks>
        /// This is meant to be a rare event.
        /// Author: Rudy Ariaz
        /// </remarks>
        /// <param name="grid">The grid in which the Colony is.</param>
        /// <param name="gameEnv">The Environment of the Colony.</param>
        public void SplitUp(Unit[,] grid, Environment gameEnv)
        {
            // Get the row and column of the Colony
            int row = Location.r, col = Location.c;

            /*
             * Try splitting in each direction, in this order:
             * Cell is in the top left corner
             * Cell is in the bottom left corner
             * Cell is in the top right corner
             * Cell is in the bottom right corner
             */
            // Iterate through the different directions of vertical splitting
            for (int rowDir = 1; rowDir >= -1; rowDir -= 2)
            {
                // Iterate through the different directions of horizontal splitting
                for (int colDir = 1; colDir >= -1; colDir -= 2)
                {
                    // Check if the split is possible in this direction
                    if (IsSplitPossible(grid, rowDir, colDir))
                    {
                        // Kill the exisitng Colony
                        this.Die(grid, gameEnv);
                        // Spread the new Cells out in the current direction
                        grid[row, col]                   = new Cell(row, col);
                        grid[row, col + colDir]          = new Cell(row, col + colDir);
                        grid[row + rowDir, col]          = new Cell(row + rowDir, col);
                        grid[row + rowDir, col + colDir] = new Cell(row + rowDir, col + colDir);
                        // Stop searching for valid splitting directions
                        break;
                    }
                }
            }
        }
Beispiel #22
0
    /// <summary>
    /// Rollback the board to cached state.
    /// </summary>
    public void RollbackGame(GameCache cache)
    {
        ClearGame();
        boardUnit  = new Unit[BoardInfo.Row, BoardInfo.Col];
        boardBread = new Unit[BoardInfo.Row, BoardInfo.Col];
        boardState = new GridState[BoardInfo.Row, BoardInfo.Col];
        playerInfo = new Dictionary <Unit.TypeEnum, int>[2] {
            new Dictionary <Unit.TypeEnum, int>(), new Dictionary <Unit.TypeEnum, int>()
        };
        restBreadNum = 0;

        for (int i = 0; i < BoardInfo.Row; i++)
        {
            for (int j = 0; j < BoardInfo.Col; j++)
            {
                boardState[i, j] = cache.descriptor.GetGridState(i, j);
                if (boardState[i, j] == GridState.Bread)
                {
                    CreateUnit(new UnitInfo(new Position(i, j), Unit.TypeEnum.Bread));
                }
                var unitInfo = cache.descriptor.GetUnitInfo(i, j);
                if (unitInfo.type >= Unit.TypeEnum.Scout && unitInfo.type <= Unit.TypeEnum.Bomb)
                {
                    CreateUnit(unitInfo);
                }
            }
        }
        for (Unit.TypeEnum type = Unit.TypeEnum.Bread; type < Unit.TypeEnum.Void; type++)
        {
            playerInfo[(int)Unit.OwnerEnum.Black][type] = cache.descriptor.GetPlayerInfo(type, Unit.OwnerEnum.Black);
            playerInfo[(int)Unit.OwnerEnum.White][type] = cache.descriptor.GetPlayerInfo(type, Unit.OwnerEnum.White);
        }
        restBreadNum = cache.descriptor.RestResource;
        SwitchTurn(cache.descriptor.Turn);
    }
Beispiel #23
0
 /// <summary>
 /// Merges the current Cell with the 3 other Cells in a 2x2 block with this Cell as the top left
 /// </summary>
 /// <param name="grid"> The grid of Units currently in the simulation </param>
 /// <param name="row"> The row of the grid that this Cell resides in </param>
 /// <param name="col"> The column of the grid that this Cell resides in </param>
 protected override void Merge(Unit[,] grid, Environment gameEnv)
 {
     KillMergedUnits(grid, gameEnv);
     // Replace the current Cell with a newly created Colony
     grid[Location.r, Location.c] =
         UnitFactory.CreateUnit(Enums.UnitType.Colony, Location.r, Location.c);
 }
Beispiel #24
0
        /// <summary>
        /// Checks if the MergeableUnit is in a position to merge (into a Colony if it
        /// is a cell, or into a Plant or Animal if it is a Colony).
        /// </summary>
        /// <param name="grid"> The grid of Units currently in the simulation </param>
        /// <param name="row"> The row of the grid that this MergeableUnit resides in. </param>
        /// <param name="col"> The column of the grid that this MergeableUnit resides in. </param>
        /// <returns> True if the MergeableUnit is the top left of a 2x2 square with other
        ///           MergeableUnits of the same species and should merge, false otherwise. </returns>
        protected bool ShouldMerge(Unit[,] grid)
        {
            // Get the type of this unit -- must merge with units of the same species
            var curType = this.GetType();
            // Get the location of the current unit
            int row = Location.r, col = Location.c;

            // if the cell is not in a space capable of forming a 2x2 square, it cannot merge
            if (!grid.InDimension(GridHelper.ROW, row + 1) ||
                !grid.InDimension(GridHelper.COLUMN, col + 1))
            {
                return(false);
            }
            // otherwise, if the surrounding 3 grids cells are of the same type, this unit should merge
            else if (grid[row, col + 1]?.GetType() == curType &&
                     grid[row + 1, col]?.GetType() == curType &&
                     grid[row + 1, col + 1]?.GetType() == curType)
            {
                return(true);
            }
            // otherwise, this unit does not meet the locational requirements to evolve
            else
            {
                return(false);
            }
        }
Beispiel #25
0
        public Grid(int width, int height)
        {
            width  = Math.Max(1, width);
            height = Math.Max(1, height);

            data = new Unit[width, height];
        }
Beispiel #26
0
        enum tags { city, grass, mount, road, water };// enum-ed tags to allow random determination of terrain tile


        // Constructors
        public Gameboard(Game1 game1)
        {
            game = game1;//store game reference

            //grid shits, need to do unit grid- fill with "empty" units
            upperIndex = new Vector2(cols, rows);

            offsetIndex = new Vector2();

            terrainGrid = new Terrain[cols, rows];
            unitGrid    = new Unit[cols, rows];
            Terrain current = new Terrain();

            current.Size = unitSize;

            defaultTex      = game1.Content.Load <Texture2D>("outline");
            current.Texture = defaultTex;

            System.Random rand = new System.Random();

            for (int i = 0; i < cols; i++)
            {
                for (int j = 0; j < rows; j++)
                {
                    current.Y                  = j * unitSize;
                    current.X                  = i * unitSize;
                    terrainGrid[i, j]          = new Terrain();
                    terrainGrid[i, j].Position = current.Position;
                    terrainGrid[i, j].Tag      = "outline";       // in case something fails and a tag cannot be generated
                    tags myTag = (tags)rand.Next(0, 5);           // this is temporary code
                    terrainGrid[i, j].Tag     = myTag.ToString(); // the tag of the tile needs to be known by this point!! figure out some sort of level loading
                    terrainGrid[i, j].Texture = game1.Content.Load <Texture2D>(terrainGrid[i, j].Tag);
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Updates an Animal with all operations that must be applied to the Animal every generation.
        /// </summary>
        /// <remarks>
        /// Called every generation.
        /// </remarks>
        /// <remarks>
        /// Author: Rudy Ariaz
        /// </remarks>
        /// <param name="grid">The grid of Units in which the Animal is.</param>
        /// <param name="gameEnv">The Environment with which the Animal interacts.</param>
        public override void Update(Unit[,] grid, Environment gameEnv)
        {
            // Apply the benefits that a Multicellular organism receives based on being in the vicinity of other
            // multicellular organisms
            ApplyCommunityBenefits(grid);
            // Perform basic operations needed for all LivingUnits
            UpdateLivingUnit(grid, gameEnv);

            // Check if the animal is hibernating
            if (IsHibernating)
            {
                // Reduce the number of generations left for hibernation
                HibernationGenerationsLeft--;
                // Try to wake up from hibernation (if there are no hibernation generations left)
                TryWake();
            }
            // Otherwise, apply the usual Animal operations
            else
            {
                // Check if the animal is starving, try to eat a plant
                if (IsStarving(gameEnv))
                {
                    // Try to eat a Plant
                    CheckPlantsToEat(grid, gameEnv);
                }
                // Check if the Unit should and can thermoregulate
                if (ShouldThermoregulate(gameEnv) && CanThermoregulate(gameEnv))
                {
                    // Thermoregulate if needed
                    Thermoregulate(gameEnv);
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Checks for Plants to eat (which are in direct contact with the Animal, so
        /// diagonal Plants are not included). Eats a Plant if a valid one is found (only one Plant can be eaten).
        /// </summary>
        /// <remarks>
        /// Author: Rudy Ariaz
        /// </remarks>
        /// <param name="grid">The Grid to use for finding Plants.</param>
        /// <param name="gameEnv">The Environment with which the Unit interacts.</param>
        private void CheckPlantsToEat(Unit[,] grid, Environment gameEnv)
        {
            // Get the row and column of the Animal
            int row = Location.r, col = Location.c;

            // Iterate through each of the directions (up, down, left, right)
            foreach (var dir in GridHelper.directions)
            {
                // Compute the new row and column of the grid block being checked
                int newRow = row + dir.Item1;
                int newCol = col + dir.Item2;
                // If the block is not within the grid, try a different direction
                if (!grid.InGridBounds(newRow, newCol))
                {
                    continue;
                }

                // Otherwise, get the neighbor in the block
                Unit neighbor = grid[newRow, newCol];
                // Check if the neighbor is a non-null Plant
                if (neighbor != null && neighbor is Plant)
                {
                    // Eat the Plant
                    EatPlant(grid, gameEnv, (Plant)neighbor);
                    // Stop looking for Plants
                    break;
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// Initialize the board controller
        /// </summary>
        public void Start()
        {
            this.Cells = new CellController[(this.GridSize * 2) + 1, (this.GridSize * 2) + 1];
            this.Units = new Unit[(this.GridSize * 2) + 1, (this.GridSize * 2) + 1];

            for (int i = -1 * this.GridSize; i <= this.GridSize; i++)
            {
                for (int j = -1 * this.GridSize; j <= this.GridSize; j++)
                {
                    if (HexDistance.Distance(0, 0, i, j) <= this.GridSize)
                    {
                        float x = i;
                        if (Math.Abs(j) % 2 == 1)
                        {
                            x = i + 0.5f;
                        }

                        var hex = (CellController)Instantiate(this.HexCellPrefab);
                        hex.transform.position = new Vector3(x * this.XScale, this.YPosition, j * this.ZScale);

                        CellCoordinate cellCoord = WorldToGameConverter.ConvertWorldToCell(hex.transform.position, this.ZScale);
                        hex.gameObject.name = "(" + cellCoord.X + ", " + cellCoord.Y + ")";
                        this.SetCell(cellCoord.X, cellCoord.Y, hex);
                        CellController cellController = hex.GetComponent <CellController>();
                        cellController.BoardController = this;
                        cellController.Coordinate      = cellCoord;
                    }
                }
            }
        }
Beispiel #30
0
        void GetNeighbours(Unit[,] table, int i, int j)
        {
            if (table[i, j] != Unit.Mine)
            {
                var neighbourmines = 0;
                for (int k = i - 1; k <= i + 1; k++)
                {
                    for (int l = j - 1; l <= j + 1; l++)
                    {
                        try
                        {
                            if (table[k, l] == Unit.Mine)
                            {
                                neighbourmines++;
                            }
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }

                table[i, j] = GetNumber(neighbourmines);
            }

            //table[i,j] = Unit.Mine;
        }
Beispiel #31
0
        public void InitializeTable(int column, int row)
        {
            if (!firstStepDone)
            {
                firstStepDone = true;
                table         = new Unit[rows, columns];
                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < columns; j++)
                    {
                        table[i, j] = Unit.Free;
                    }
                }

                var rnd       = new Random();
                var minesLeft = mines;

                while (minesLeft > 0)
                {
                    int mineX;
                    int mineY;
                    do
                    {
                        mineX = rnd.Next(0, columns);
                        mineY = rnd.Next(0, rows);
                    }while ((mineX == column && mineY == row) || table[mineX, mineY] == Unit.Mine);

                    table[mineX, mineY] = Unit.Mine;
                    minesLeft--;
                }

                SetNumbers(table);
            }
        }
Beispiel #32
0
        /// <summary>
        /// Assumes playerUnits and enemyUnits are already initialized (non-null).
        /// </summary>
        /// <param name="board"></param>
        /// <param name="tiles"></param>
        /// <param name="playerUnits"></param>
        /// <param name="enemyUnits"></param>
        public Game(
            Unit[,] board,
            Tile[,] tiles,
            List <Unit> playerUnits,
            List <Unit> enemyUnits)
        {
            allUnits = new List <Unit>();

            this.board       = board;
            this.tiles       = tiles;
            this.playerUnits = playerUnits;
            this.enemyUnits  = enemyUnits;

            foreach (Unit unit in playerUnits)
            {
                allUnits.Add(unit);
                unit.team = Teams.Player;
            }
            foreach (Unit unit in enemyUnits)
            {
                allUnits.Add(unit);
                unit.team = Teams.Enemy;
            }

            foreach (Unit unit in allUnits)
            {
                unit.board = board;
                unit.tiles = tiles;
            }
        }
        public Engine(int mapWidth, int mapHeight)
        {
            currentTick = 0;
            futureUpdates = new Dictionary<int, List<Unit>>();
            map = new EngineMap(this, mapWidth, mapHeight);
            unitTypes = new List<UnitType>();
            tileTypes = new List<TileType>();
            players = new List<Player>();
            units = new List<Unit>();
            unitGrid = new Unit[map.width, map.height];
            unitQuadtrees = new Dictionary<Player, Quadtree>();

            idCounter = 0;

            map.Initialize();
            List<Position> goldTiles = new List<Position>();
            List<Position> ironTiles = new List<Position>();
            List<Position> manaTiles = new List<Position>();
            ai1 = new AI(this, null, goldTiles, ironTiles, manaTiles);
            ai2 = new AI(this, null, goldTiles, ironTiles, manaTiles);
        }
Beispiel #34
0
    /// <summary>
    /// Start a new game, refresh all the data
    /// </summary>
    public void NewGame()
    {
        ClearGame();
        boardUnit = new Unit[BoardInfo.Row, BoardInfo.Col];
        boardBread = new Unit[BoardInfo.Row, BoardInfo.Col];
        boardState = new GridState[BoardInfo.Row, BoardInfo.Col];
        playerInfo = new Dictionary<Unit.TypeEnum, int>[2]{new Dictionary<Unit.TypeEnum, int>(), new Dictionary<Unit.TypeEnum, int>()};

        for (int r = 0; r < BoardInfo.Row; r++)
            for (int c = 0; c < BoardInfo.Col; c++)
                boardState[r, c] = GridState.Void;

        boardState[BoardInfo.Base[0].R, BoardInfo.Base[0].C] = GridState.Base0;
        boardState[BoardInfo.Base[1].R, BoardInfo.Base[1].C] = GridState.Base1;

        foreach(Position pos in BoardInfo.BreadList)
            CreateUnit(new UnitInfo(pos, Unit.TypeEnum.Bread));
        restBreadNum = BoardInfo.BreadList.Length;

        foreach (UnitInfo info in BoardInfo.InitUnitList)
            CreateUnit(info);
    }
Beispiel #35
0
    public void Create(FightCtller ctl, DirType dir)
    {
        m_dir = dir;
        m_ctller = ctl;

        m_units = new Unit[UnitCount.Y, UnitCount.X];
        for (int y = 0; y < Units.GetLength(0); ++y)
        {
            for (int x = 0; x < Units.GetLength(1); ++x)
            {
                m_units[y, x] = new Unit(new Int2D(x, y), null);
                m_units[y, x].Position = CalcUnitPosition(m_units[y, x].Index, dir);
            }
        }
    }
Beispiel #36
0
    void Awake()
    {
        Cells = new Unit[Width, Height];

        _gridCollider = GetComponent<BoxCollider>();
        _gc = GameController.Get();

        CreateGrid();
    }