CellGrid class keeps track of the game, stores cells, units and players objects. It starts the game and makes turn transitions. It reacts to user interacting with units or cells, and raises events related to game progress.
Inheritance: MonoBehaviour
 public CellGridStateUnitSelected(CellGrid cellGrid, Unit unit)
     : base(cellGrid)
 {
     _unit = unit;
     _pathsInRange = new List<Cell>();
     _unitsInRange = new List<Unit>();
 }
    public override void Play(CellGrid cellGrid)
    {
        cellGrid.CellGridState = new CellGridStateAiTurn(cellGrid);
        _cellGrid = cellGrid;

        StartCoroutine(Play()); //Coroutine is necessary to allow Unity to run updates on other objects (like UI).
                                //Implementing this with threads would require a lot of modifications in other classes, as Unity API is not thread safe.
    }
 void SelectCharacter(CellGrid cellGrid)
 {
     var unit = cellGrid.Units.FindAll(u => u.PlayerNumber.Equals(PlayerNumber)).FirstOrDefault();
     if (unit != null)
     {
         manager.actualPlayer = unit.GetComponent<Actor>();
         cameraController.target = unit.transform;
     }
 }
Beispiel #4
0
    public Vector3 findPosition(CellGrid cellgrid, int gridSize)
    {
        int cellPosition = cellgrid.Cells.IndexOf(Cell);
        int i            = cellPosition / gridSize;
        int j            = (cellPosition % gridSize) / 2;

        if ((cellPosition % gridSize) % 2 != 0)
        {
            j += 1;
        }
        int     k      = (cellPosition % gridSize / 2);
        Vector3 vector = (new Vector3(i, j, k));

        SimplifyHexVector3(ref vector);
        return(vector);
    }
Beispiel #5
0
        public void BeforeEachTest()
        {
            Cell[,] cells = new Cell[GridSize, GridSize];

            for (int column = 0; column < GridSize; column++)
            {
                for (int row = 0; row < GridSize; row++)
                {
                    cells[column, row] = new Cell(CellState.Dead);
                }
            }
            gameCellGrid = new CellGrid(cells);


            game = new Game(gameCellGrid);
        }
Beispiel #6
0
    // **TODO** Implémenter les dégâts supplémentaires au centre.

    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellgrid)
    {
        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Skill", true);
        anim.SetBool("Idle", false);

        foreach (var receiver in receivers)
        {
            int damage = UnityEngine.Random.Range(MinDamage, MaxDamage + 1);
            caster.DealDamage2(receiver, damage);
        }

        caster.ActionPoints--;
        SetCooldown();
    }
Beispiel #7
0
 public void Initialize(CellGrid cellGrid, Canvas canvas)
 {
     if (!IsInitialized)
     {
         IsInitialized = true;
         Regions       = new List <Region>();
         this.cellGrid = cellGrid;
         SegmentGridByElevation(canvas);
         CalculateAllRegionPortals();
         GenerateColliders();
     }
     else
     {
         Debug.LogWarning("RegionManager.Initialize() has already been called!");
     }
 }
        // TODO: fix this entire region (temporary interface hack)

        // erase wall labels in all cells
        private void eraseLabels()
        {
            CellGrid grid = board.getGridRef();

            for (uint r = 0; r < grid.rowcnt; r++)
            {
                for (uint c = 0; c < grid.colcnt; c++)
                {
                    for (int l = 0; l < Cell.wcnt; l++)
                    {
                        board[r, c].lbl[l]     = "";
                        board[r, c].lbltemp[l] = "";
                    }
                }
            }
        }
        // iterate through available moves on given grid
        private bool iterateMove(ref CellGrid grid, ref Move m, uint attr, uint minPathlen)
        {
            // search for the next sensible move starting from the last move
            do
            {
                // get the next wall of the cell, in the following order:  top -> lef -> bot -> rig
                // initially m.wall will result in Cell.none (because it has initial value Cell.none)
                do
                {
                    m.wall = ((m.wall << 1) & Cell.all);
                }while (                                                 // (attr & skipunsensible) == 0 && // if unsensible should be skipped, check all walls of a cell
                    ((m.wall == Cell.bot && m.row != grid.rowcnt - 1) || // skip bot wall except if the cell is in the bottom row
                     (m.wall == Cell.rig && m.col != grid.colcnt - 1))); // skip rig wall except if the cell is in the right column

                // if all walls of the cell were exausted, move to the next cell
                if (m.wall == Cell.none)
                {
                    do
                    {
                        // move to the next cell
                        if (++m.col >= grid.colcnt)  // m.col will initially be 0 (because it has initial value uint.MaxValue)
                        {
                            m.col = 0;
                            if (++m.row >= grid.rowcnt)
                            {
                                // m.row = 1000;  //TEST

                                m = null; // there are no moves left to play
                                return(false);
                            }
                        }
                    }while (grid[m.row, m.col].getWallCnt() == 4 || // skip cells having all walls
                            ((attr & skip2) == skip2 && grid[m.row, m.col].getWallCnt() == 2)); // if required, skip cells having two walls

                    // the first wall of the cell to check is at the top
                    m.wall = Cell.top;
                }
            }while (grid[m.row, m.col].hasWall(m.wall) || // repeat the search until the chosen wall does not exist in the chosen cell, then try that move
                    ((attr & skip2) == skip2 && // if cells already having two walls should be skipped, do so
                     ((m.wall == Cell.lef && m.col > 0 && grid[m.row, m.col - 1].getWallCnt() == 2) ||
                      (m.wall == Cell.rig && m.col < grid.colcnt - 1 && grid[m.row, m.col + 1].getWallCnt() == 2) ||
                      (m.wall == Cell.top && m.row > 0 && grid[m.row - 1, m.col].getWallCnt() == 2) ||
                      (m.wall == Cell.bot && m.row < grid.rowcnt - 1 && grid[m.row + 1, m.col].getWallCnt() == 2))) ||
                    ((attr & skipunsafe) == skipunsafe && !grid.isMoveSafe(m.row, m.col, m.wall)) ||
                    ((attr & skipunsensible) == skipunsensible && !grid.isMoveSensible(m.row, m.col, m.wall, minPathlen)));
            return(true);
        }
Beispiel #10
0
    public override void HandleCapture()
    {
        Unit[]   units = GameObject.Find("Units Parent").GetComponentsInChildren <Unit>();
        CellGrid grid  = GameObject.Find("CellGrid").GetComponent <CellGrid>();

        if (!Cell.IsTaken)
        {
            HitPoints = 20;
            return;
        }
        foreach (Unit u in units)
        {
            if (!(u is Building) && u.transform.position.x == this.transform.position.x && u.transform.position.y == this.transform.position.y)
            {
                if (u.canCapture && u.isAbleToCapture && u.PlayerNumber != this.PlayerNumber && grid.CurrentPlayerNumber == u.PlayerNumber)
                {
                    int capValue = (u.HitPoints / 10) + 1;
                    if (capValue > 10)
                    {
                        capValue = 10;
                    }

                    HitPoints -= capValue;
                    StartCoroutine("DamageFlash");

                    if (HitPoints <= 0)
                    {
                        PlayerNumber = u.PlayerNumber;
                        UpdateColor();
                        HitPoints = 20;
                        faction   = u.faction;
                    }
                }
                else if (grid.CurrentPlayerNumber == u.PlayerNumber)
                {
                    HitPoints = 20;
                    if (u.PlayerNumber == this.PlayerNumber)
                    {
                        u.HitPoints += 20;
                        u.UpdateHpBar();
                    }
                }
                return;
            }
        }
        HitPoints = 20;
    }
Beispiel #11
0
        public void ReformatCellGrid(UInt16 newWidth, UInt16 newHeight, bool forceRedraw)
        {
            ONIPlannerSubControl[,] newGrid = new ONIPlannerSubControl[newWidth, newHeight];

            if (newWidth == CellGrid.GetLength(0) && newHeight == CellGrid.GetLength(1))
            {
                return;
            }

            if (CellGrid == null)
            {
                newGrid.Initialize();
            }

            else
            {
                for (int x = 0; x < newWidth; x++)
                {
                    for (int y = 0; y < newHeight; y++)
                    {
                        if (CellGrid.GetLength(0) > newWidth || CellGrid.GetLength(1) > newHeight)
                        {
                            newGrid[x, y] = new ONIPlannerSubControl();
                        }

                        else
                        {
                            newGrid[x, y] = CellGrid[x, y];
                        }
                    }
                }
            }

            CellGrid = newGrid;

            if (forceRedraw)
            {
                for (int x = 0; x < newWidth; x++)
                {
                    for (int y = 0; y < newHeight; y++)
                    {
                        CellGrid[x, y].NeedsRedraw = true;
                        CellGrid[x, y].Refresh();
                    }
                }
            }
        }
Beispiel #12
0
        // Check if grid has element and it's upper-left corner is positioned at (x, y)
        private bool CheckIfHasElementOnPosition(int x, int y, CellGrid element, bool marked)
        {
            for (var i = 0; i < element.height; i++)
            {
                for (var j = 0; j < element.width; j++)
                {
                    if (element[i, j] != 'b' &&
                        ((marked && this[x + i, y + j] != 'm') ||
                         (!marked && this[x + i, y + j] == 'b')))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Beispiel #13
0
        public static BitGrid ToBitGrid(CellGrid cellGrid)
        {
            BitGrid grid = new BitGrid(cellGrid.Width, cellGrid.Height);

            for (var row = 0; row < grid.Height; row++)
            {
                for (var cell = 0; cell < grid.Width; cell++)
                {
                    var gridCell = cellGrid[row][cell];
                    grid[row][cell] |= (!gridCell.North)? (int)Directions.N:0;
                    grid[row][cell] |= (!gridCell.East)? (int)Directions.E:0;
                    grid[row][cell] |= (!gridCell.South)? (int)Directions.S:0;
                    grid[row][cell] |= (!gridCell.West)? (int)Directions.W:0;
                }
            }
            return(grid);
        }
Beispiel #14
0
    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellGrid)
    {
        int selfHeal = (int)Mathf.Floor((caster.TotalHitPoints - caster.HitPoints) / 2);

        caster.HitPoints += selfHeal;
        if (caster.HitPoints > caster.TotalHitPoints)
        {
            caster.HitPoints = caster.TotalHitPoints;
        }
        SecondWindBuff Buff = new SecondWindBuff();

        caster.Buffs.Add(Buff);
        Buff.Apply(caster);

        caster.ActionPoints--;
        SetCooldown();
    }
Beispiel #15
0
        // Return cells coordinates related to grid of element,
        // upper-left corner of wich is positioned at (x, y)
        private List <Tuple <int, int> > GetCellsCoordinatesOfElement(int x, int y, CellGrid element)
        {
            var coordinates = new List <Tuple <int, int> >();

            for (var i = 0; i < element.height; i++)
            {
                for (var j = 0; j < element.width; j++)
                {
                    if (element[i, j] != 'b' && this[x + i, y + j] == 'm')
                    {
                        coordinates.Add(Tuple.Create(x + i, y + j));
                    }
                }
            }

            return(coordinates);
        }
Beispiel #16
0
        private static string GetMaximumPopulationText(int terrainId, CellGrid cellGrid, HexOffsetCoordinates hexPoint)
        {
            var gameConfigCache = CallContext <GameConfigCache> .GetData("GameConfigCache");

            var terrain = gameConfigCache.GetTerrainConfigById(terrainId);

            if (!terrain.CanSettleOn)
            {
                return(string.Empty);
            }

            var catchment = cellGrid.GetCatchment(hexPoint.Col, hexPoint.Row, 2);
            var maxPop    = BaseFoodLevel.DetermineBaseFoodLevel(catchment);
            var text      = $"Maximum Pop - {maxPop}";

            return(text);
        }
Beispiel #17
0
    // **TODO** Implémenter les dégâts supplémentaires au centre.

    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellgrid)
    {
        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Skill", true);
        anim.SetBool("Idle", false);

        for (int i = 0; i < 3; ++i)
        {
            int randomReceiver = UnityEngine.Random.Range(0, receivers.Count);
            int damage         = UnityEngine.Random.Range(MinDamage, MaxDamage + 1);
            caster.DealDamage2(receivers[randomReceiver], damage);
        }


        caster.ActionPoints--;
        SetCooldown();
    }
Beispiel #18
0
        public TapeGrid(string tape, int width, int height, CellGrid element)
            : base(tape, width, height)
        {
            var reflections = element.GetCellsReflections();

            for (var i = 0; i <= 3; i++)
            {
                elements[i * 2] =
                    new CellGrid(reflections[i * 2],
                                 i % 2 == 0 ? element.width : element.height,
                                 i % 2 == 0 ? element.height : element.width);

                elements[i * 2 + 1] =
                    new CellGrid(reflections[i * 2 + 1],
                                 i % 2 == 0 ? element.width : element.height,
                                 i % 2 == 0 ? element.height : element.width);
            }
        }
Beispiel #19
0
    // **TODO** Implémenter les dégâts supplémentaires au centre.

    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellgrid)
    {
        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Skill", true);
        anim.SetBool("Idle", false);

        foreach (var receiver in receivers)
        {
            DefenceBuff ArmorVoidBuff = new DefenceBuff(2, 1.5f);
            receiver.Buffs.Add(ArmorVoidBuff);
            ArmorVoidBuff.Apply(receiver);
        }


        caster.ActionPoints--;
        SetCooldown();
    }
    public void UpdateAgent_Movement()
    {
        if (isDead)
        {
            return;
        }

        if (movementMode == MovementMode.Pathing)
        {
            movementController.FixedUpdate_MovementController();
        }
        else if (movementMode == MovementMode.Steering)
        {
            simpleVehicleModel.UpdateSteering();
        }

        Cell = CellGrid.GetCell(transform.position);
    }
Beispiel #21
0
    protected void PathFind(int x, int y)
    {
        // Pathfind to player
        CellGrid cellGrid = LevelGen.CellGrid;

        GridCell targetCell  = cellGrid.Grid[x, y];
        GridCell currentCell = cellGrid.GetCellAtPos(transform.position);

        List <Vector3> path = cellGrid.FindPathWorld(targetCell, currentCell);

        if (path.Count > 1)
        {
            // Move towards next cell
            Vector3 dir = (path[1] - transform.position).normalized;
            TurnTowards(dir);
            Move(dir);
        }
    }
        // return id of winning player (invalid id if there is no such player)
        private int getWinnerId()
        {
            CellGrid grid = board.getGridRef();

            // if the board still has uncircled cells, do nothing
            if (grid.getCircledCnt() != grid.getCellCnt())
            {
                return(Player.invalid_id);
            }

            int  id_best    = 0;  // id of winning player(s)
            uint ccc_best   = 0;  // circled cell count of winning player(s)
            uint winner_cnt = 0;  // number of winning players, should be one if there is a clear winner

            // for all players
            for (uint id = 0, ccc; id < player_cnt; id++)
            {
                // save current player circle cell count
                ccc = player[id].getCircledCellCnt();

                // if current player beats previous players
                if (ccc_best < ccc)
                {
                    // update best player variable, and reset the winning players counter
                    id_best    = (int)id;
                    ccc_best   = ccc;
                    winner_cnt = 1;
                }
                else if (ccc_best == ccc)
                {
                    // if the current player has the same circled cell count as the best player, increase the winning players counter
                    winner_cnt++;
                }
            }

            // if there are more winning players, then the game is a tie
            if (winner_cnt > 1)
            {
                id_best = Player.invalid_id;
            }

            // return winning player id
            return(id_best);
        }
Beispiel #23
0
    public override void Apply(Unit caster, List <Cell> cells, CellGrid cellGrid)
    {
        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Skill", true);
        anim.SetBool("Idle", false);

        foreach (var currentCell in cells)
        {
            if (currentCell.Occupent != null)
            {
                int damage = UnityEngine.Random.Range(MinDamage, MaxDamage + 1);
                caster.DealDamage2(currentCell.Occupent, damage);
            }
        }

        caster.ActionPoints--;
        SetCooldown();
    }
Beispiel #24
0
    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellGrid)
    {
        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Attack", true);
        anim.SetBool("Idle", false);

        foreach (var receiver in receivers)
        {
            int damage = UnityEngine.Random.Range(MinDamage, MaxDamage + 1);
            caster.DealDamage2(receiver, damage);
            RootedDebuff debuff = new RootedDebuff();
            receiver.Buffs.Add(debuff);
            debuff.Apply(receiver);
        }

        caster.ActionPoints--;
        SetCooldown();
    }
Beispiel #25
0
    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellGrid)
    {
        foreach (var receiver in receivers)
        {
            int  damage = UnityEngine.Random.Range(MinDamage, MaxDamage + 1);
            Unit victim = MoveCasterToTarget(caster, receiver, cellGrid);
            Debug.Log(victim);
            Debug.Log(damage);
            caster.DealDamage2(victim, damage);
        }

        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Attack", true);
        anim.SetBool("Idle", false);

        caster.ActionPoints--;
        SetCooldown();
    }
Beispiel #26
0
    private void EliminateByRout(Unit defeater)
    {
        CellGrid grid = GameObject.Find("CellGrid").GetComponent <CellGrid>();

        foreach (Unit u in grid.Units)
        {
            if (u is Building && u.PlayerNumber == this.PlayerNumber)
            {
                u.PlayerNumber = defeater.PlayerNumber;
                (u as Building).UpdateColor();
                u.GetComponent <Renderer>().material.color = (u as Unit).LeadingColor;
            }
            else if (u.PlayerNumber == this.PlayerNumber)
            {
                u.DestroyUnit(defeater, 100);
            }
        }
        grid.CheckForEndGame();
    }
Beispiel #27
0
        public T Invoke(int width, int height, CellGrid cellGrid)
        {
            return(Execute(() =>
            {
                var cells = new List <Cell>();

                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        var cell = new Cell(x, y, cellGrid);
                        cell.CellEvaluationState = new CellStateEvaluated(cell);
                        cells.Add(cell);
                    }
                }

                return OnComplete(cells);
            }));
        }
Beispiel #28
0
    // **TODO** Implémenter les dégâts supplémentaires au centre.

    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellgrid)
    {
        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Skill", true);
        anim.SetBool("Idle", false);
        foreach (var receiver in receivers)
        {
            receiver.HitPoints += 40;
            Buff DoT = receiver.Buffs.Find(b => b.isDot);
            if (DoT != null)
            {
                receiver.Buffs.Remove(DoT);
            }
        }


        caster.ActionPoints--;
        SetCooldown();
    }
Beispiel #29
0
        public void KillCellIfItIsUnderPopulated()
        {
            Cell[,] cells = new Cell[GridSize, GridSize];

            for (int column = 0; column < GridSize; column++)
            {
                for (int row = 0; row < GridSize; row++)
                {
                    cells[column, row] = new Cell(CellState.Dead);
                }
            }

            cells[5, 5] = new Cell(CellState.Alive);

            CellGrid cellGrid = new CellGrid(cells);

            cellGrid.Iterate();

            Assert.IsTrue(cellGrid.Cells[5, 5].State == CellState.Dead);
        }
Beispiel #30
0
    /// <summary>
    /// Attacking unit calls Defend method on defending unit.
    /// </summary>
    protected virtual void Defend(Unit other, int damage)
    {
        MarkAsDefending(other);
        HitPoints -= DamageCalculator(other, damage, 0, Cell.defenseValue);
        GameObject.Find("DamageSound").GetComponent <AudioSource>().Play();

        StartCoroutine("DamageFlash");

        //(55 * ((100 / (100 + 0 * 10))) / (10 - Math.Ceiling(10)))
        //HitPoints -= Mathf.Clamp(damage - DefenceFactor, 1, damage);  //Damage is calculated by subtracting attack factor of attacker and defence factor of defender. If result is below 1, it is set to 1.
        //This behaviour can be overridden in derived classes.
        if (UnitAttacked != null)
        {
            UnitAttacked.Invoke(this, new AttackEventArgs(other, this, damage));
        }

        if (HitPoints <= 0)
        {
            CellGrid grid     = GameObject.Find("CellGrid").GetComponent <CellGrid>();
            Player   myPlayer = grid.Players.Find(p => p.PlayerNumber.Equals(this.PlayerNumber));
            if (grid.Units.FindAll(u => u.PlayerNumber.Equals(this.PlayerNumber) && !(u is Building)).Count <= 1)
            {
                myPlayer.EliminatePlayer(false, other);
                grid.CheckForEndGame();
            }

            DestroyUnit(other, damage);

            return;
        }
        if (CanCounterAttack(other))
        {
            AttackFactor = (int)(DamageChart.damageValues[this.GetDamageType().ToString().ToUpper()][other.GetArmorType().ToString().ToUpper()] * damageMultiplier * other.armorMultiplier);
            //AttackFactor = DamageChart.damageValues[this.GetType().ToString()][other.GetType().ToString()];
            other.HitPoints -= other.DamageCalculator(this, AttackFactor, 0, 0);

            other.StartCoroutine("DamageFlash");
        }

        UpdateHpBar();
    }
Beispiel #31
0
    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellGrid)
    {
        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Attack", true);
        foreach (Unit u in receivers)
        {
            if (caster.Cell.GetDistance(u.Cell) == 1)
            {
                int damage = UnityEngine.Random.Range(17, 21);
                caster.DealDamage2(u, damage);
            }
            else
            {
                int damage = UnityEngine.Random.Range(MinDamage, MaxDamage + 1);
                caster.DealDamage2(u, damage);
            }
        }
        caster.ActionPoints--;
        SetCooldown();
    }
Beispiel #32
0
        public void DoNotReviveCellIfItHas1Neighbour()
        {
            Cell[,] cells = new Cell[GridSize, GridSize];

            for (int column = 0; column < GridSize; column++)
            {
                for (int row = 0; row < GridSize; row++)
                {
                    cells[column, row] = new Cell(CellState.Dead);
                }
            }

            cells[5, 5] = new Cell(CellState.Dead);
            cells[4, 4] = new Cell(CellState.Alive);

            CellGrid cellGrid = new CellGrid(cells);

            cellGrid.Iterate();

            Assert.IsTrue(cellGrid.Cells[5, 5].State == CellState.Dead);
        }
Beispiel #33
0
    // **TODO** Implémenter les dégâts supplémentaires au centre.

    public override void Apply(Unit caster, List <Unit> receivers, CellGrid cellgrid)
    {
        Animator anim = caster.GetComponentInChildren <Animator>();

        anim.SetBool("Skill", true);
        anim.SetBool("Idle", false);

        foreach (var receiver in receivers)
        {
            int heal = UnityEngine.Random.Range(MinDamage, MaxDamage + 1);
            receiver.HitPoints += heal;
            if (receiver.HitPoints > receiver.TotalHitPoints)
            {
                receiver.HitPoints = receiver.TotalHitPoints;
            }
        }


        caster.ActionPoints--;
        SetCooldown();
    }
 public CellGridStateAiTurn(CellGrid cellGrid) : base(cellGrid)
 {      
 }
 public CellGridStateTurnChanging(CellGrid cellGrid) : base(cellGrid)
 {
 }
Beispiel #36
0
 public override void Play(CellGrid cellGrid)
 {
     base.Play(cellGrid);
     SelectCharacter(cellGrid);
 }
    public CellGridStateTurnChanging(CellGrid cellGrid) : base(cellGrid)
    {
		//cellGrid.EndTurn ();
		Debug.LogWarning("turn changing");
    }
 public CellGridStateWaitingForInput(CellGrid cellGrid) : base(cellGrid)
 {
 }
    public void Regenerate()
    {
        // Clean up
        Ungenerate();

        // Regenerate maze
        maze.Regenerate();

        // Make the mesh seriously like 5x the resolution of the original maze for destructivity
        hiResGrid = new Cell[maze.Grid.GetLength(0) * MAZE_RESOLUTION,
                                     maze.Grid.GetLength(1) * MAZE_RESOLUTION];

        for (int x = 0; x < maze.Grid.GetLength(0); ++x)
        {
            for (int y = 0; y < maze.Grid.GetLength(1); ++y)
            {
                for (int ix = 0; ix < MAZE_RESOLUTION; ++ix)
                {
                    for (int iy = 0; iy < MAZE_RESOLUTION; ++iy)
                    {
                        Cell oldCell = maze.Grid[x, y];

                        int newX = x * MAZE_RESOLUTION + ix;
                        int newY = y * MAZE_RESOLUTION + iy;

                        Cell newCell = new Cell(oldCell);
                        newCell.position = new Point(newX, newY);

                        hiResGrid[newX, newY] = newCell;
                    }
                }
            }
        }

        // Store a list of empty spaces
        emptySpaces = new List<GridCell>();

        // Copy maze to pathfinding grid
        int width = hiResGrid.GetLength(0);
        int height = hiResGrid.GetLength(1);
        Grid = new GridCell[width, height];
        for (int x = 0; x < width; ++x)
        {
            for (int y = 0; y < height; ++y)
            {
                Grid[x, y] = new GridCell(x, y, hiResGrid[x, y].visited);

                if (Grid[x, y].Accessible)
                    emptySpaces.Add(Grid[x, y]);
            }
        }

        // Create cell grid for pathfinding
        cellGrid = CellGrid;

        // Reset enemy pathfinding data
        NonplayerCharacter.ResetPathfinding();

        // Get list of empty cells
        List<GridCell> emptyCellsCopy = new List<GridCell>(emptySpaces);

        // Pick random deadend for player
        GridCell playerSpawnCell = emptyCellsCopy[Random.Range(0, emptyCellsCopy.Count)];

        // Remove this dead end from the list so that no enemies can spawn there
        emptyCellsCopy.Remove(playerSpawnCell);

        // Spawn the player there
        Vector3 playerPos = cellGrid.GetCellPos(playerSpawnCell);
        playerPos.z = 0;

        GameObject playerObj = ((Component)GameObject.FindObjectOfType(typeof(PlayerCharacter))).gameObject;
        playerObj.transform.position = playerPos;

        // Create enemies and do the same
        enemies = new GameObject("Enemies");
        for (int i = 0; i < enemyCount; ++i)
        {
            // Pick random place for enemy to spawn
            GridCell enemySpawnCell = emptyCellsCopy[Random.Range(0, emptyCellsCopy.Count)];

            Vector3 enemyPos = cellGrid.GetCellPos(enemySpawnCell);
            enemyPos.z = 0;

            GameObject enemy = (GameObject)GameObject.Instantiate(enemyPrefab,
                                                                  enemyPos,
                                                                  Quaternion.identity);
            enemy.GetComponent<NonplayerCharacter>().target = playerObj;

            enemy.transform.parent = enemies.transform;

            // Add a slight force to enemy so they get unstuck if they're overlapping another character
            enemy.rigidbody.AddForce(new Vector3(0.1f, 0.1f));
        }

        // Spawn powerups in maze
        PowerupManager powerupManager = (PowerupManager)GameObject.FindObjectOfType(typeof(PowerupManager));
        powerupManager.SetOpenSpaces(cellGrid, emptySpaces);
        powerupManager.SpawnPowerups();

        // Create mesh for level
        mesh = MeshGenerator.GenerateMesh(hiResGrid);

        // Asign mesh to mesh filter
        GetComponent<MeshFilter>().mesh = mesh;
        GetComponent<MeshCollider>().sharedMesh = mesh;

        // Create lights on walls
        if (wallLightPrefab != null)
        {
            CreateLights();
        }
    }
 public override void Play(CellGrid cellGrid)
 {
     cellGrid.CellGridState = new CellGridStateWaitingForInput(cellGrid);
 }
	// Used to reset the pathfinding when the level is regenerated
	public static void ResetPathfinding()
	{		
		gridWidth = LevelGen.CellGrid.Width;
		gridHeight = LevelGen.CellGrid.Height;
		
		// Allocate grids
		cellStates = new CellState[gridWidth, gridHeight];
		pathFindingGrid = new GridCell[gridWidth, gridHeight];
		
		// Initialise state grid
		for (int x = 0; x < gridWidth; ++x)
			for (int y = 0; y < gridHeight; ++y)
		{
			cellStates[x, y] = CellState.UNKNOWN;
		}
		
		// Initialise pathfinding grid
		for (int x = 0; x < gridWidth; ++x)
			for (int y = 0; y < gridHeight; ++y)
		{
			pathFindingGrid[x, y] = new GridCell(x, y, false);
		}
		
		cellGrid = new CellGrid(pathFindingGrid, LevelGen.Instance.transform, LevelGen.MAZE_RESOLUTION);
		
		currentTargets.Clear();
	}
 public void SetOpenSpaces(CellGrid cellGrid, List<GridCell> openSpaces)
 {
     this.cellGrid = cellGrid;
     this.openSpaces = new List<GridCell>(openSpaces);
     this.powerups = new List<Powerup>();
 }
 public PathNodeFromGrid(CellGrid grid, GridCell cell)
 {
     this.grid = grid;
     this.cell = cell;
 }
 protected CellGridState(CellGrid cellGrid)
 {
     _cellGrid = cellGrid;
 }
 void SelectFirstEnemy(CellGrid cellGrid)
 {
     this.cellGrid = cellGrid;
     units = cellGrid.Units.FindAll(u => u.PlayerNumber.Equals(PlayerNumber)).ToList();
     NextMonster();
 }
 public override void Play(CellGrid cellGrid)
 {
     base.Play(cellGrid);
     SelectFirstEnemy(cellGrid);
 }
Beispiel #47
0
 /// <summary>
 /// Method is called every turn. Allows player to interact with his units.
 /// </summary>         
 public abstract void Play(CellGrid cellGrid);
 public CellGridStateGameOver(CellGrid cellGrid) : base(cellGrid)
 {
 }