Beispiel #1
0
    private void GetMoveOpponet(List <HexCoord> attackTilesNotCanBeCount, List <HexCoord> attackTilesCanBeCount, List <Player> opponetsNotCanBeCount, bool isDirect)
    {
        List <Player>   tempUser    = GameMidiator.m_Instance.m_PlayerManager.GetUserPlayers(null, false);
        List <HexCoord> tempPlayers = GameMidiator.m_Instance.m_PlayerManager.GetPlayerHexes(new HexCoord(-999, -999));

        for (int i = 0; i < tempUser.Count; i++)
        {
            Player          player     = tempUser[i];
            List <HexCoord> playerRing = HexCoord.HexRing(player.m_Hex, isDirect ? 1 : 2);
            List <HexCoord> tiles      = attackTilesCanBeCount;
            if (!player.GetIsCanAttack(isDirect))
            {
                opponetsNotCanBeCount.Add(player);
                tiles = attackTilesNotCanBeCount;
            }
            for (int j = 0; j < playerRing.Count; j++)
            {
                HexCoord hex = playerRing[j];
                if (!tiles.Contains(hex) && m_StageMapManager.GetMapTile(hex) != null && !tempPlayers.Contains(hex))
                {
                    tiles.Add(hex);
                }
            }
        }
    }
Beispiel #2
0
    /// <summary>
    /// Get the corners of a QR-space rectangle containing every cell touching an XY-space rectangle.
    /// </summary>
    public static HexCoord[] CartesianRectangleBounds(Vector2 cornerA, Vector2 cornerB)
    {
        Vector2 min = new Vector2(Math.Min(cornerA.x, cornerB.x), Math.Min(cornerA.y, cornerB.y));
        Vector2 max = new Vector2(Math.Max(cornerA.x, cornerB.x), Math.Max(cornerA.y, cornerB.y));

        HexCoord[] results =
        {
            HexCoord.AtPosition(min),
            HexCoord.AtPosition(max)
        };
        Vector2 pos = results[0].Position();

        if (pos.y - 0.5f >= min.y)
        {
            results[0] += m_AxialDirections[4];
        }
        else if (pos.x >= min.x)
        {
            results[0] += m_AxialDirections[3];
        }
        pos = results[1].Position();
        if (pos.y + 0.5f <= max.y)
        {
            results[1] += m_AxialDirections[1];
        }
        else if (pos.x <= max.x)
        {
            results[1] += m_AxialDirections[0];
        }
        return(results);
    }
Beispiel #3
0
    public int DugoutRegistration(HexCoord currentHex, UnitColor color, UnitType type)
    {
        int num = 1;

        if (color == UnitColor.White)
        {
            foreach (UnitType member in whitePieceList)
            {
                if (member == type)
                {
                    num++;
                }
            }
            whitePieceList.Add(type);
        }
        if (color == UnitColor.Black)
        {
            foreach (UnitType member in blackPieceList)
            {
                if (member == type)
                {
                    num++;
                }
            }
            blackPieceList.Add(type);
        }

        boardList.Add(PieceStringHelper(color, type, num));
        boardDict[PieceStringHelper(color, type, num)] = currentHex;

        return(num);
    }
Beispiel #4
0
 void RpcAttackSuccess(HexCoord attackerCoord)
 {
     if (state == State.SelectAttactTarget && this.towerCoord == attackerCoord)
     {
         SwitchTo(State.Idle);
     }
 }
Beispiel #5
0
    /// <summary>
    /// Determines whether this hex is within a specified rectangle.
    /// </summary>
    /// <returns><c>true</c> if this instance is within the specified rectangle; otherwise, <c>false</c>.</returns>
    public bool IsWithinRectangle(HexCoord cornerA, HexCoord cornerB)
    {
        if (m_R > cornerA.m_R && m_R > cornerB.m_R || m_R < cornerA.m_R && m_R < cornerB.m_R)
        {
            return(false);
        }
        bool reverse  = cornerA.m_Offset > cornerB.m_Offset;          // Travel right to left.
        bool offset   = cornerA.m_R % 2 != 0;                         // Starts on an odd row, bump alternate rows left.
        bool trim     = Math.Abs(cornerA.m_R - cornerB.m_R) % 2 == 0; // Even height, trim alternate rows.
        bool odd      = (m_R - cornerA.m_R) % 2 != 0;                 // This is an alternate row.
        int  width    = Math.Abs(cornerA.m_Offset - cornerB.m_Offset);
        bool hasWidth = width != 0;

        if (reverse && (odd && (trim || !offset) || !(trim || offset || odd)) ||
            !reverse && (trim && odd || offset && !trim && hasWidth))
        {
            width -= 1;
        }
        int x = (m_Offset - cornerA.m_Offset) * (reverse ? -1 : 1);

        if (reverse && odd && !offset ||
            !reverse && offset && odd && hasWidth)
        {
            x -= 1;
        }
        return(x <= width && x >= 0);
    }
Beispiel #6
0
 public HexGridCell(AxialCoord axialCoord, TCellValue value)
 {
     AxialCoord = axialCoord;
     CubeCoord  = HexCoord.AxialToCube(axialCoord);
     Value      = value;
     CacheNeighbourCoords();
 }
Beispiel #7
0
    /// <summary>
    /// Returns all of the tiles within the movement range of the given tile.
    /// </summary>
    /// <returns>A HashSet of HexCoord objects that are reachable.</returns>
    /// <param name="startNode">The coordinate of the starting point.</param>
    /// <param name="range">The movement range of the given unit.</param>
    public HashSet<HexCoord> getMovementRange(HexCoord startNode, int range)
    {
        HashSet<HexCoord> moveableTiles = new HashSet<HexCoord>();

        Queue<HexCoord> searchQueue = new Queue<HexCoord>();
        Dictionary<HexCoord, int> ranges = new Dictionary<HexCoord, int>();

        searchQueue.Enqueue(startNode);
        ranges[startNode] = 0;

        while(searchQueue.Count > 0) {
            HexCoord currentNode = searchQueue.Dequeue();

            if(ranges[currentNode] <= range) {
                moveableTiles.Add(currentNode);

                foreach(HexCoord neighbor in currentNode.getNeighbors()){
                    if(!ranges.ContainsKey(neighbor) && tiles.ContainsKey(neighbor)) {
                        //TODO: Also confirm that this is a movable square

                        ranges[neighbor] = ranges[currentNode] + 1;
                        searchQueue.Enqueue(neighbor);
                    }
                }
            }
        }

        moveableTiles.Remove(startNode);
        return moveableTiles;
    }
Beispiel #8
0
    public virtual List <HexCoord> GetAttackRangeWithTarget(HexCoord targetGridPosition, List <HexCoord> excludeHex = null)
    {
        List <HexCoord> range = new List <HexCoord>();

        if (GetIsCanAttack(true))
        {
            range.AddRange(HexTile.GetCubeRingTile(targetGridPosition, 1));
        }
        if (GetIsCanAttack(false))
        {
            range.AddRange(HexTile.GetCubeRingTile(targetGridPosition, 2));
        }
        if (excludeHex != null)
        {
            for (int i = 0; i < range.Count; i++)
            {
                if (excludeHex.Contains(range[i]))
                {
                    range.Remove(range[i]);
                }
            }
        }

        return(range);
    }
Beispiel #9
0
    Sprite AddBoardCell (HexCoord c)
    {
        var texture = Resources.Textures.Tile;
        var textureHeight = texture.GetHeight();
        float scale = 2f / textureHeight;

        var s = new Sprite
        {
            Texture = texture,
            Scale = new Vector2(scale, scale),
            ZIndex = (int)ZLayers.Background,
            Position = c.Position(),
            Modulate = BoardColor
        };
        board.AddChild(s);
        var overlay = new Sprite
        {
            Texture = Resources.Textures.BoardGradient,
            Scale = new Vector2(scale, scale),
            ZIndex = (int)ZLayers.Background+1,
            Position = c.Position()
        };
        board.AddChild(overlay);
        return s;
    }
Beispiel #10
0
        public Tile GetNeighbourInDirection(string direction)
        {
            Vector3        offset       = neighbourDictionary[direction];
            HexCoordinates neighbourHex = HexCoord.GetNeighBourHexCoordinates(offset);

            return(GetNeighbourTileByHexCoordinate(neighbourHex));
        }
Beispiel #11
0
 public void CancelMove()
 {
     transform.position = HexTilePos();
     m_PlayerUI.SetPosition(HexTilePos());
     m_HexTarget  = m_Hex;
     _PlayerState = PlayerState.Move;
 }
Beispiel #12
0
 public HexCoord Add(HexCoord c)
 {
     return(new HexCoord()
     {
         x = x + c.x, y = y + c.y
     });
 }
    public void ColorCel(HexCoord idx, int val)
    {
        Texture2D tex = (Texture2D)quad.renderer.sharedMaterial.mainTexture;

        Color[] cels;
        if (val == numCelTypes - 1)
        {
            cels = template.GetPixels(0, 0, celSize, celSize);
        }
        else
        {
            cels = template.GetPixels(val * celSize, 0, celSize, celSize);
        }

        int x0 = (celSize / 2) * ((height - 1 - idx.j) % 2) + (width - 1 - idx.i) * celSize;
        int y0 = pixelHeight - 1 - (height - 1 - idx.j) * (celSize - heightOffset);

        for (int x = 0; x < celSize; x++)
        {
            for (int y = 0; y < celSize; y++)
            {
                Color c = cels[x + (celSize - 1 - y) * celSize];
                if ((val == numCelTypes - 1) && (c.a != 0))
                {
                    tex.SetPixel(x0 + x, (y0 - y), Color.clear);
                }
                else if (c.a != 0)
                {
                    tex.SetPixel(x0 + x, (y0 - y), c);
                }
            }
        }
        tex.Apply();
    }
Beispiel #14
0
        private bool IsHexAroundSelection(HexCoord coord)
        {
            var distance = coord.WorldDistance(selectedUnit.Unit.Coord);
            var terra    = map.Level.Map.Map[coord.X, coord.Y];

            return(distance > 0.5f && distance < 1.1f && terra.IsAvailableForUnit(selectedUnit.Unit));
        }
    public void SelectPiece(int placementType)
    {
        Debug.Log("Piece Selected: " + this.transform.name);
        selected = true;

        startHex = currentHex;
        hexController.HighlightStart(currentHex);

        boardManager.SelectingNewPiece();

        this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, layerHt2);  //Move up to second layer
        this.transform.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotation;
        if (placementType == 1)
        {
            specificBehavior.GetEligibleFirstPlacement();
        }
        else if (placementType == 2)
        {
            specificBehavior.GetEligibleSecondPlacement();
        }
        else
        {
            specificBehavior.GetEligible();
        }
    }
Beispiel #16
0
    // Find the hex that overlaps a certain x,y point
    public void HighlightHex(HexCoord hex)
    {
        Vector2    hexPos  = hex.Position();
        GameObject hexDisp = null;

        //Brute force method to get hex display associated with a certain HexCoord
        int   i            = 0;
        float smallestDist = Mathf.Infinity;

        foreach (Transform child in HexDisplays.transform)
        {
            float dist = Vector2.SqrMagnitude(hexPos - (Vector2)child.position);

            if (dist < smallestDist)
            {
                smallestDist = dist;
                hexDisp      = child.gameObject;
            }
            i++;
        }

        //Highlight the hex
        if (hexDisp != null)
        {
            hexDisp.GetComponent <HexDisplayControl>().Highlight(true);
        }
    }
Beispiel #17
0
    void PointEdit()
    {
        RaycastHit hit;

        if (Physics.Raycast(cameraTransform.position, cameraTransform.forward, out hit, 5))
        {
            Chunk    chunk        = world.GetChunk(hit.point);
            HexCoord hexUnrounded = chunk.PosToHex(hit.point);
            HexCell  hexCenter    = hexUnrounded.ToHexCell();
            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    for (int k = -1; k <= 1; k++)
                    {
                        HexCell hex              = new HexCell(hexCenter.x + i, hexCenter.y + j, hexCenter.z + k);
                        Vector3 point            = chunk.HexToPos(hex);
                        Vector3 c                = 2 * point - hexUnrounded.ToVector3();
                        float   distanceStrength = 10 / (Mathf.Pow(c.x, 2) + Mathf.Pow(c.y, 2) + Mathf.Pow(c.z, 2));
                        Vector3 changeNormal     = 10 * new Vector3(-2 * c.x / (Mathf.Pow(Mathf.Pow(c.x, 2) + Mathf.Pow(c.y, 2) + Mathf.Pow(c.z, 2), 2)),
                                                                    -2 * c.y / (Mathf.Pow(Mathf.Pow(c.x, 2) + Mathf.Pow(c.y, 2) + Mathf.Pow(c.z, 2), 2)),
                                                                    -2 * c.z / (Mathf.Pow(Mathf.Pow(c.x, 2) + Mathf.Pow(c.y, 2) + Mathf.Pow(c.z, 2), 2)));
                        chunk.EditPointValue(hex, distanceStrength);
                        chunk.EditPointNormal(hex, changeNormal);
                        gameObject.GetComponent <LoadChunks>().AddToUpdateList(chunk.chunkCoords);
                    }
                }
            }
        }
    }
Beispiel #18
0
    public bool LoadStageData(SaveDataStore saveData)
    {
        m_StageIndex = saveData.m_StageIndex - 1;
        if (m_StageIndex < 0 || m_StageIndex >= m_StageAssets.Length)
        {
            return(false);
        }
        m_Container = ObjectSaveLoad.JsonDataLoad <MapContainer>(m_StageAssets[m_StageIndex].text);
        m_Container.InitTileDataMap();
        m_ShopItemList   = m_Container.shopItemList;
        m_ShopWeaponList = m_Container.shopWeaponList;

        m_StageMapManager.CreateStageMap(m_Container);
        for (int i = 0; i < saveData.m_ChestStates.Count; i++)
        {
            HexCoord hex = new HexCoord(saveData.m_ChestStates[i].m_LocX, saveData.m_ChestStates[i].m_LocY);
            m_StageMapManager.GetMapTile(hex).SetChestState(saveData.GetChestState(hex));
        }

        List <PlayerRecord> userPlayerRecords  = GetUserPlayerRecords(saveData.m_UserPlayerRecords, saveData.m_StagePlayerRecords);
        List <PlayerRecord> enemyPlayerRecords = GetEnemyPlayerRecords(saveData.m_StageEnemyRecords);

        m_PlayerManager.GenetarePlayers(userPlayerRecords);
        m_PlayerManager.GenetarePlayers(enemyPlayerRecords);
        m_ScenarionManager.SetScenarion(m_Container.scenarionList, saveData.m_RemoveScenaroList);
        return(true);
    }
    public void SelectPiece(int placementType)
    {
        Debug.Log("Piece Selected: " + this.transform.name);
        selected = true;

        startHex = currentHex;
        hexController.HighlightStart(currentHex);

        boardManager.SelectingNewPiece();

        this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, layerHt2);  //Move up to second layer
        this.transform.GetComponent <Rigidbody>().constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotation;
        if (placementType == 1)
        {
            specificBehavior.GetEligibleFirstPlacement();
        }
        else if (placementType == 2)
        {
            specificBehavior.GetEligibleSecondPlacement();
        }
        else
        {
            specificBehavior.GetEligible();
        }
    }
    // Use this for initialization
    void Start()
    {
        total = 469;            //Hard code the total number of hexes for now. 469 is for hex board with radius of 12
        HexBoard = new HexCoord[total];
        int index = 0;

        int startRow = 0;
        int endRow = rows;

        for (int i = -columns; i < columns+1; i++)
        {
            for (int j = startRow; j < endRow + 1; j++)
            {

                HexCoord newHex = new HexCoord(i, j);
                HexBoard[index] = newHex;
                //Debug.Log(HexBoard[index].ToString());
                index++;
            }

            if (i < 0)
                startRow--;
            else
                endRow--;
        }
        //Debug.Log(index);

        InitializeHexes ();
    }
    //Moves piece to target hex. Used for undoing moves and moving piece back to start position. Checks for beetle stacking at target hex
    void SnapToHex(HexCoord hex)
    {
        Vector3 snapPos = hex.Position();

        snapPos.z = 3.0f;                                       //Move up high first to avoid collisions with other pieces
        this.transform.position = snapPos;                      //Snap to x,y position of target hex
        //this.transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, 0f));    //Snap to default rotation

        //For beetles the target hex might be occupied. In that case, fix the z distance and don't allow gravity. Also make sure it's a beetle that's coming from the board. If coming from the dugout then treat as a normal piece
        if (specificBehavior.type == BoardManager.UnitType.Beetle && specificBehavior.active == BoardManager.Active.Board)
        {
            if (boardManager.beetleDict[hex] > 0) //Check if there was a stacked beetle at target hex
            {
                Vector3 temp       = this.transform.position;
                int     numBeetles = boardManager.beetleDict[hex];
                temp.z = 0.2f + 0.4f * (numBeetles);          //Position will scale up if there are multiple beetles
                this.transform.position = temp;
                this.transform.GetComponent <Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
            }
            else
            {
                this.transform.GetComponent <Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionY;
            }
        }
        // If piece is not a beetle then treat it normally
        else
        {
            this.transform.GetComponent <Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionY;
        }

        currentHex = hexController.GetNearestHex(this.transform.position);
    }
Beispiel #22
0
    public void spawn_map(int radius = 8)
    {
        /// <summary>
        /// Spawns empty hex tiles on the tactical map. Size is determined by the <paramref name="radius"/> parameter
        /// <param name="radius">Radius of the tactical map</param>
        /// </summary>

        hex_dict = new Dictionary <int, Dictionary <int, Dictionary <int, HexCoord> > >();

        for (int a = -radius + 1; a < radius; a++)
        {
            hex_dict.Add(a, new Dictionary <int, Dictionary <int, HexCoord> >());
            for (int b = -radius + 1; b < radius; b++)
            {
                hex_dict[a].Add(b, new Dictionary <int, HexCoord>());
                int c = -(a + b);

                if (Mathf.Abs(c) > radius)
                {
                    continue;
                }

                GameObject tile = Instantiate(Resources.Load("HexTile")) as GameObject;
                HexCoord   hxc  = tile.GetComponent <HexCoord>();
                hxc.set_abc(a, b, c);

                hex_dict[a][b].Add(c, hxc);
            }
        }
    }
Beispiel #23
0
    public void CalculatePaths(Puzzle puzzle, HexCoord coord)
    {
        GD.Print($"Placing tile {Name} ({GetPathString()})");

        //propagate neighbor paths
        for (int side = 0; side < directions.Length; side++)
        {
            var neighborCell = puzzle.Map.TryGetCell(coord + directions[side]);
            if (neighborCell != null)
            {
                if (neighborCell.Value.Tile is PuzzleTileHex neighbor)
                {
                    GD.Print($"Side {side} neighbor is {neighbor.Name} ({neighbor.GetPathString()})");
                    //get the path id of the neighboring tile
                    var pathID = neighbor.Paths[(side + 3) % 6];
                    GD.Print($"Neighbor path ID is {pathID}");
                    PropagateIncomingPath(side, pathID);
                }
            }
        }

        //ensure all sides have path IDs
        for (int side = 0; side < directions.Length; side++)
        {
            if (Paths[side] == 0)
            {
                var id = puzzle.GetNextPathId();
                Paths[side] = id;
                Paths[LineDescriptions[side]] = id;
            }
        }
    }
Beispiel #24
0
    /// <summary>
    /// Send mesh data to the mesh and apply after affects
    /// </summary>
    void MeshProcedure()
    {
        List <Vector3> posVerts = new List <Vector3>();

        foreach (HexCell hexCell in verts)
        {
            HexCoord      hex   = hexCell.ToHexCoord();
            HexWorldCoord point = HexToWorldHex(hex);
            normals.Add(GetNormal(hex));
            Vector3 offset = new Vector3();
            Vector3 smooth = new Vector3();
            if (world.smoothLand)
            {
                Vector3 norm = GetNormal(hex);
                norm = norm.normalized * sqrt3 / 2;
                float A = GetNoise(PosToHex(World.HexToPos(point) + norm));
                float B = GetNoise(PosToHex(World.HexToPos(point) - norm));
                float T = 0;
                smooth = norm.normalized * ((A + B) / 2 - T) / ((A - B) / 2) * -sqrt3 / 2;
            }
            if (world.offsetLand)
            {
                offset = .4f * World.GetNormalNonTerrain((HexToPos(hexCell) + smooth) * 27);
            }
            posVerts.Add(HexToPos(hexCell) + offset + smooth);
        }
        mesh.SetVertices(posVerts);
        mesh.SetTriangles(tris, 0);
        mesh.SetNormals(normals);
    }
Beispiel #25
0
    void OnDrop()
    {
        ZIndex = oldZIndex;
        puzzle.HideCursor();

        var coord   = HexCoord.AtPosition(Position);
        var mapCell = puzzle.Map.TryGetCell(coord);

        if (!IsValidDrop(mapCell))
        {
            puzzle.SoundPlayerWhoosh.Play(0);
            puzzle.ResetTile(this);
            return;
        }

        puzzle.SoundPlayerDrop.Play(0);

        MakeFixed();

        puzzle.Map.SetCell(new CellInfo(coord, this));
        puzzle.SnapTileToCell(this, coord);
        puzzle.SpawnTile();

        CalculatePaths(puzzle, coord);

        if (puzzle.Map.TileCount == puzzle.Map.CellCount)
        {
            OnFail();
        }
    }
Beispiel #26
0
        public void Move(AbstractUnit unit, HexCoord target)
        {
            unit.Move(target);

            foreach (var enemy in enemies)
            {
                var distance = unit.Coord.WorldDistance(enemy.Coord);
                var shooted  = distance < (enemy.AttackRadius + 0.1f);
                if (shooted)
                {
                    if (unit is Airplane && enemy is AntiAir && enemy.ResistanceCurrent > 0)
                    {
                        unit.IsDead = true;
                        enemy.Shooting();
                        playerArmy.Remove(unit);
                        break;
                    }
                    else if (unit is Soldier && enemy is Bunker && enemy.ResistanceCurrent > 0)
                    {
                        unit.IsDead = true;
                        enemy.Shooting();
                        playerArmy.Remove(unit);
                        break;
                    }
                }
            }
            Debug.Log("Army " + playerArmy.Count);
            UpdateControl();
            CheckEnd();
        }
Beispiel #27
0
    public static Vector3 Coord2Pos(HexCoord coord)
    {
        float x = coord.gridX * RowSpace;
        float z = coord.NeedOffset ? ((coord.gridY + 0.5f) * ColSpace) : (coord.gridY * ColSpace);

        return(new Vector3(x, 0, z));
    }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        HexCoord coordinates = new HexCoord(property.FindPropertyRelative("x").intValue, property.FindPropertyRelative("z").intValue);

        position = EditorGUI.PrefixLabel(position, label);
        GUI.Label(position, coordinates.ToString());
    }
    void NetworkSyncMove(Vector3 pos, bool placement, Vector2 strt)
    {
        //Translate start and current positions back to HexCoords
        HexCoord strtHex = hexController.GetNearestHex(strt);
        HexCoord currHex = hexController.GetNearestHex(pos);

        Debug.Log("Is Mine?: " + this.GetComponent <PhotonView>().isMine);
        if (this.GetComponent <PhotonView>().isMine)
        {
            //Take normal actions, piece has already been moved on this client
            hexController.ClearOutlines();
        }

        else
        {
            this.transform.position = pos;  //Move to new position
        }

        //If moving from the dugout
        if (placement)
        {
            specificBehavior.NewPiecePlacement();    //Register piece properly as it's first placement
        }
        //If moving on the board
        else
        {
            boardManager.MovePiece(strtHex, currHex, specificBehavior.color, specificBehavior.type, this.gameObject);    //Make the move official in the board manager
        }

        hexController.ShowLastMove(strtHex, currHex);
    }
Beispiel #30
0
    // Use this for initialization
    void Start()
    {
        total    = 469;         //Hard code the total number of hexes for now. 469 is for hex board with radius of 12
        HexBoard = new HexCoord[total];
        int index = 0;

        int startRow = 0;
        int endRow   = rows;

        for (int i = -columns; i < columns + 1; i++)
        {
            for (int j = startRow; j < endRow + 1; j++)
            {
                HexCoord newHex = new HexCoord(i, j);
                HexBoard[index] = newHex;
                //Debug.Log(HexBoard[index].ToString());
                index++;
            }

            if (i < 0)
            {
                startRow--;
            }
            else
            {
                endRow--;
            }
        }
        //Debug.Log(index);


        InitializeHexes();
    }
Beispiel #31
0
    /// <summary>
    /// This finds actual array indexes by reversing offset and scaling applied to HexCoord.
    /// </summary>
    /// <param name="coordinate">World Position of Tile.</param>
    public HexTile GetHexTile(Vector2 coordinate)
    {
        Vector2 noOffset  = new Vector2(coordinate.x - _startPos.x, coordinate.y - _startPos.z) * _hexScaleFactor;
        Vector2 qrVector2 = HexCoord.VectorXYtoQR(noOffset);

        return(GetHexTile(Mathf.RoundToInt(qrVector2.x), Mathf.RoundToInt(qrVector2.y)));
    }
Beispiel #32
0
 public void SetCoord(HexCoord coord, bool isPassable = true)
 {
     _hexCoord   = coord;
     name        = coord.ToString();
     _isPassable = isPassable;
     AutoSetState();
 }
Beispiel #33
0
 void Update()
 {
     if (lastPosition != transform.position)
     {
         lastPosition = transform.position;
         coord        = HexagonUtils.Pos2Coord(transform.position);
     }
 }
    public void DecreasePositionControl(HexCoord position, int player)
    {
        // Remove the mark of the current player from the position.
        PositionControl control;
        if (PositionControls.TryGetValue(position, out control))
            control.TowerOfPlayer = Player.NoPlayer;

        // recalculate position controls
        foreach (var neighbor in ControlledPositionsAround(position, GameRuleSettings.Instance.Tower.ControlDistance))
        {
            neighbor.DecreaseControl(player);
        }
    }
 /// <summary>
 /// Gets infos about who controls the positions around a given position.
 /// </summary>
 public IEnumerable<PositionControl> ControlledPositionsAround(HexCoord position, int distance)
 {
     foreach(HexCoord neighbor in NeighborhoodRespectingBorders(position, distance))
     {
         PositionControl control;
         if (!PositionControls.TryGetValue(neighbor, out control))
         {
             control = new PositionControl(neighbor, HexBoard);
             PositionControls.Add(neighbor, control);
         }
         yield return control;
     }
 }
    public void IncreasePositionControl(HexCoord position, int player)
    {
        // add a PositionControl for the now occupied position, if missing.
        PositionControl control;
        if (!PositionControls.TryGetValue(position, out control))
            PositionControls.Add(position, control = new PositionControl(position, HexBoard));
        control.TowerOfPlayer = player;

        // recalculate position controls
        foreach (var neighbor in ControlledPositionsAround(position, GameRuleSettings.Instance.Tower.ControlDistance))
        {
            neighbor.IncreaseControl(player);
        }
    }
    // create a new tower at selected position
    public bool CreateTower(HexCoord position, int playerNumber)
    {
        if (!HexBoard.IsPositionOnBoard(position) // check borders
            || IsTowerAt(position) // check if tower does not already exists, before creating new tower
            || NumStartedShootings > 0)
            return false;

        GameObject newTower = (GameObject)Instantiate(TowerPrefab);
        newTower.transform.SetParent(transform);
        newTower.transform.localPosition = position.Position3d() * HexBoard.TileScale;
        newTower.transform.rotation = Quaternion.Euler(0, 90, 0); // point the turret to the right
        var towerControl = newTower.GetComponent<TowerControl>();
        towerControl.playerNumber = playerNumber;
        towerControl.SetColor(playerNumber);
        Positions.IncreasePositionControl(position, playerNumber);
        return true;
    }
Beispiel #38
0
 public void SetTilePlayerColor(HexCoord position, int player)
 {
     var meshFilter = GetComponent<MeshFilter>();
     var mesh = meshFilter.sharedMesh;
     var vertices = mesh.vertices;
     var uv = mesh.uv;
     // Find the indices of the vertices of
     var v = position.Corner3d(0) * TileScale;
     int i;
     for (i = 0; i < vertices.Length && vertices[i] != v; i++) ;
     if (i == vertices.Length)
         return; // vertex not found -> position probably not on board
     for (int corner = 0; corner < 6; corner++, i++)
     {
         uv[i] = GetUvForCornerAndPlayer(corner, player);
     }
     mesh.uv = uv;
 }
Beispiel #39
0
    public Planet(HexCoord coordinate, string name, string description, int subdivisions)
    {
        this.coordinate = coordinate;
        this.name = name;
        this.description = description;
        this.subdivisions = subdivisions;

        //Generate array for storing terrain
        Dictionary<int, HashSet<int>> graph = HexPlanet.createOnlyPlanetGraph(subdivisions);
        terrain = new int[graph.Count];

        //Initialize
        for(int i = 0; i < terrain.Length; ++i) {
            terrain[i] = WATER;
        }

        //Seed some land
        for(int i = 0; i < 3; ++i) {
            terrain[Random.Range(0, terrain.Length)] = GRASSLAND;
        }

        //Evolve land
        for(int i = 0; i < 3; ++i) {
            int[] new_terrain = new int[terrain.Length];
            System.Array.Copy(terrain, new_terrain, terrain.Length);

            for(int j = 0; j < terrain.Length; ++j) {
                if(terrain[j] == GRASSLAND) {
                    foreach(int neighbor in graph[j]) {
                        if(Random.value > 0.1) {
                            new_terrain[neighbor] = GRASSLAND;
                        }
                    }
                }
            }

            terrain = new_terrain;
        }

        //
        //terrain[0] = 2;
        //terrain[1] = 2;
    }
Beispiel #40
0
 private void OnFieldSelected(HexCoord position)
 {
     var gridTowers = GetComponent<GridTowers>();
     if (gridTowers.CreateTower(position, Player.Current))
         EndTurn();
 }
Beispiel #41
0
 public bool IsPositionOnBoard(HexCoord position)
 {
     var point = position.OddRToOffset();
     return point.x >= 0 && point.x < SizeX && point.y >= 0 && point.y < SizeZ;
 }
    public Vector2 FindNearest(Vector2 pos)
    {
        // Find the hex that overlaps a certain x,y point
        //Debug.Log(pos);
        nearestHex = HexCoord.AtPosition(pos);
        Vector2 hexPos = nearestHex.Position();

        return hexPos;
    }
    // Outline a single hex
    public void ShowLastMove(HexCoord strt, HexCoord curr)
    {
        ClearLastMove();
        outlineObject = (GameObject)Instantiate(outlinePrefabTall);
        outlineObject.transform.position = curr.Position();

        HighlightStart(strt);
    }
    // Used when a piece moves to update the lists
    public void MovePiece(HexCoord prevHex, HexCoord newHex, UnitColor color, UnitType type, GameObject obj)
    {
        if (type == UnitType.Beetle) //If beetle then we need to update lists differently
        {
            if (occupiedList.Contains(newHex)) //If beetle is moving on top of another piece
            {
                beetleDict[newHex]++;   //Add beetle on top
                CoverPieceBelow(obj.transform.position);
                //Don't add beetle to occupied list since hex is already occupied
            }
            else //If new hex is unoccupied then add beetle to occupied list
            {
                occupiedList.Add(newHex);
                colorDict[newHex] = color;
                typeDict[newHex] = type;
            }
            if (beetleDict[prevHex] > 0)    //If moving a beetle from a stacked position
            {
                beetleDict[prevHex]--;      //Decrement beetle count at previous hex
                UncoverPieceBelow(new Vector3(prevHex.Position().x, prevHex.Position().y, 5.0f)); //Define ray starting point far enough above prev position
            }
            else  //Only remove prevHex from lists if no other piece is at previous position
            {
                occupiedList.Remove(prevHex);
                colorDict.Remove(prevHex);
                typeDict.Remove(prevHex);
            }
        }
        else //If any other move type then change lists and dict as normal;
        {
            occupiedList.Remove(prevHex);
            colorDict.Remove(prevHex);
            typeDict.Remove(prevHex);
            beetleDict.Remove(prevHex);

            occupiedList.Add(newHex);
            colorDict[newHex] = color;
            typeDict[newHex] = type;
            beetleDict[newHex] = 0;
        }
    }
    //Get all eligible hexes for movement that touch a played piece but don't have a piece on them. Exclude the currently selected piece
    public List<HexCoord> GetOuterHexes(HexCoord start)
    {
        List<HexCoord> eligibleList = new List<HexCoord>();
        List<HexCoord> occupiedListMod = new List<HexCoord>(occupiedList);  //Copy list

        occupiedListMod.Remove(start);                                   //Exclude selected piece from neighbor search
        //Iterate through occupied start and find all neighbors. Add them to the possibly eligible list
        foreach (HexCoord hc in occupiedListMod)
        {
            foreach (HexCoord adj in hc.Neighbors())
            {
                if (!occupiedListMod.Contains(adj) && !eligibleList.Contains(adj)) //Don't add any occupied hexes or duplicates
                {
                    eligibleList.Add(adj);
                }
            }
        }
        //Finally, remove the selected hex from the list because you can't move to the same place that the piece started
        eligibleList.Remove(start);

        return eligibleList;
    }
    // Outline a single hex
    public void OutlineHex(HexCoord hex)
    {
        outlineObject = (GameObject)Instantiate(outlinePrefab);
        LineRenderer lineRend = outlineObject.GetComponent<LineRenderer>();
        int vertexCount = 7;
        lineRend.SetVertexCount(vertexCount);
        int ind = 0;
        foreach (Vector2 pos in hex.Corners()){
            Vector3 pos3d = new Vector3(pos.x, pos.y, 0.02f);   //Offset in the z direction slightly above board
            lineRend.SetPosition(ind, pos3d);

            if (ind == 0)
                lineRend.SetPosition(vertexCount-1, pos3d); //Also set the end vertex the same as the start point

            ind++;
        }
    }
    //NOT USED
    public void HighlightNearestDeprecated(Vector2 pos)
    {
        // Find the hex that overlaps a certain x,y point
        //Debug.Log(pos);
        nearestHex = HexCoord.AtPosition(pos);
        Vector2 hexPos = nearestHex.Position();
        GameObject hexDisp = null;

        //Brute force method to get hex display associated with a certain HexCoord
        int i = 0;
        //int ind = 0;
        float smallestDist = Mathf.Infinity;
        foreach(Transform child in HexDisplays.transform)
        {
            float dist = Vector2.SqrMagnitude(hexPos - (Vector2)child.position);

            if (dist < smallestDist){
                smallestDist = dist;
                //ind = i;
                hexDisp = child.gameObject;
            }
            i++;
        }

        //Highlight the hex
        if (hexDisp != null && hexDisp != prevHexDisp) {
            if (prevHexDisp != null)
            {
                prevHexDisp.GetComponent<HexDisplayControl>().Highlight(false);
            }
            hexDisp.GetComponent<HexDisplayControl>().Highlight(true);

            prevHexDisp = hexDisp;
        }
    }
    // Used when a piece first enters the board to populate the type and color lists. Return piece number (if the second white spider then returns 2)
    public void RegisterPiece(HexCoord currentHex, UnitColor color, UnitType type)
    {
        //int index = GetIndex(currentHex);

        //colorList[index] = color;
        //typeList[index] = type;

        occupiedList.Add(currentHex);
        colorDict[currentHex] = color;
        typeDict[currentHex] = type;
        beetleDict[currentHex] = 0; //No beetles on top
    }
    //Checks whether moving a piece from start hex to test hex will be jumping a gap or not.
    //I.e. Most pieces can't make a move that would have them not be in contact with the hive
    //during the move
    bool IsMoveGapJumping(HexCoord initial, HexCoord current, HexCoord test)
    {
        bool gapJumped = true;      //Initialize as true. Must be proved to be false
        List<HexCoord> currentNeighbors = new List<HexCoord>();
        List<HexCoord> testNeighbors = new List<HexCoord>();
        List<HexCoord> occupiedListMod = new List<HexCoord>(occupiedList);  //Copy list
        occupiedListMod.Remove(initial);                                   //Exclude piece in question from neighbor search

        //Find all neighbor pieces at current location
        foreach (HexCoord nh in current.Neighbors())
        {
            if (occupiedListMod.Contains(nh))   //If neighbor hex is occupied
            {
                currentNeighbors.Add(nh);       //Add to current neighbors list
            }
        }

        //Find all neighbor pieces at current location
        foreach (HexCoord nh in test.Neighbors())
        {
            if (occupiedListMod.Contains(nh))   //If neighbor hex is occupied
            {
                testNeighbors.Add(nh);       //Add to test neighbors list
            }
        }

        //If no neighbors are the same at new location then the piece WOULD be jumping a gap
        foreach (HexCoord hex in testNeighbors)
        {
            if (currentNeighbors.Contains(hex))
            {
                gapJumped = false;
            }
        }

        return gapJumped;
    }
    //Check if a hex is unreachable (completely surrounded or only have one open space next to it) ///This doesn't remove more complex unreachable areas (like a multiple hex open area that is surrounded)
    bool IsHexUnreachable(HexCoord testHex)
    {
        bool unreachable = false;

        int neighborCount = CountOccupiedNeighbors(testHex);

        if (neighborCount >= 5)
        {
            unreachable = true;
        }

        return unreachable;
    }
 int GetIndex(HexCoord hex)
 {
     int index = 0;
     foreach (HexCoord hc in HexBoard)
     {
         if (hc == hex)
         {
             break;
         }
         index++;
     }
     return index;
 }
 int CountOccupiedNeighbors(HexCoord hex)
 {
     int neighborCount = 0;
     foreach (HexCoord nh in hex.Neighbors())
     {
         if (occupiedList.Contains(nh))
         {
             neighborCount++;
         }
     }
     return neighborCount;
 }
Beispiel #53
0
    private void BuildMesh()
    {
        /*
        1. Loop through hex grid in offset-coordinates (http://www.redblobgames.com/grids/hexagons/#map-storage)
        2. For each hex pos, get coordinates of each corner
        3. Use hash table to get vertex index of corner, store corner with index if not found.
        4. Create triangles based on vertex indices stored in hash table.
        */

        int numTiles = SizeX * SizeZ;
        int numTriangles = numTiles * 4;
        //var verticesMap = new Dictionary<Vector3, int>();
        var vertices = new Vector3[numTiles * 6];
        var triangles = new int[numTriangles * 3];
        var hexes = new HexCoord[numTiles];
        var uvMap = new Dictionary<int, Vector2>();

        int triIndex = 0;
        int vIndex = 0;
        int x, z, h = 0;
        for (x = 0; x < SizeX; x++)
            for (z = 0; z < SizeZ; z++)
            {
                hexes[h] = HexCoord.FromOffsetOddR(x, z);
                var corners = hexes[h].Corners().Select(p => new Vector3(p.x * TileScale, 0, p.y * TileScale)).ToArray();
                triangles[triIndex++] = vIndex + 0;
                triangles[triIndex++] = vIndex + 5;
                triangles[triIndex++] = vIndex + 4;

                triangles[triIndex++] = vIndex + 0;
                triangles[triIndex++] = vIndex + 4;
                triangles[triIndex++] = vIndex + 3;

                triangles[triIndex++] = vIndex + 0;
                triangles[triIndex++] = vIndex + 3;
                triangles[triIndex++] = vIndex + 1;

                triangles[triIndex++] = vIndex + 1;
                triangles[triIndex++] = vIndex + 3;
                triangles[triIndex++] = vIndex + 2;

                int cornerIndex = 0;
                foreach (var v in corners)
                {
                    vertices[vIndex] = v;
                    var uv = GetUvForCornerAndPlayer(cornerIndex, Player.NoPlayer);
                    uvMap.Add(vIndex, uv);
                    vIndex++;
                    cornerIndex++;
                }
                h++;
            }

        var mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.normals = vertices.Select(i => Vector3.up).ToArray();
        mesh.uv = uvMap.OrderBy(pair => pair.Key).Select(pair => pair.Value).ToArray();
        mesh.triangles = triangles;
        var meshFilter = GetComponent<MeshFilter>();
        meshFilter.mesh = mesh;
        var meshCollider = GetComponent<MeshCollider>();
        meshCollider.sharedMesh = mesh;
    }
    public int DugoutRegistration(HexCoord currentHex, UnitColor color, UnitType type)
    {
        int num = 1;
        if (color == UnitColor.White)
        {
            foreach (UnitType member in whitePieceList)
            {
                if (member == type)
                {
                    num++;
                }
            }
            whitePieceList.Add(type);
        }
        if (color == UnitColor.Black)
        {
            foreach (UnitType member in blackPieceList)
            {
                if (member == type)
                {
                    num++;
                }
            }
            blackPieceList.Add(type);
        }

        boardList.Add(PieceStringHelper(color, type, num));
        boardDict[PieceStringHelper(color, type, num)] = currentHex;

        return num;
    }
    public void HighlightStart(HexCoord startHex)
    {
        if (startHighlight != null)
            Destroy(startHighlight);

        startHighlight = (GameObject)Instantiate(highlightPrefab);
        startHighlight.GetComponent<HighlightController>().StartHex();
        startHighlight.transform.position = startHex.Position();
    }
 public HexCoord GetNearestHex(Vector2 pos)
 {
     nearestHex = HexCoord.AtPosition(pos);
     return nearestHex;
 }
Beispiel #57
0
 public Spaceship(HexCoord coordinate, string type, Player owner)
 {
     this.coordinate = coordinate;
     this.type = type;
     this.owner = owner;
 }
Beispiel #58
0
 public Star(HexCoord coordinate, string name, string description)
 {
     this.coordinate = coordinate;
     this.name = name;
     this.description = description;
 }
 // Outline a single hex
 public void OutlineHexTall(HexCoord hex)
 {
     outlineObject = (GameObject)Instantiate(outlinePrefabTall);
     outlineObject.transform.position = hex.Position();
 }
    //Returns a list of eligible moves for a given piece
    public List<HexCoord> EligibleMovesByPiece(HexCoord start, UnitType type)
    {
        Debug.Log("Eligible Start " + start);
        //Start with outer hexes
        List<HexCoord> eligibleList = GetOuterHexes(start);
        List<HexCoord> eligibleListMod = new List<HexCoord>();    //Make a blank list
        switch (type)
        {
            case UnitType.Ant:
                //Copy eligible list. Ant can move to any outer position.
                eligibleListMod = new List<HexCoord>(eligibleList);
                RemoveUnreachableHexes(eligibleListMod);                //Next remove unreachable locations.
                ////Currently I don't check to see whether a move would have the ant squeeze through a hole that's too small
                ////A way to implement this would be to check space by space in a move chain. If any space is unreachable then
                ////the chain would stop.
                break;

            case UnitType.Queen:
                //Queen can only move one hex away from start. Check for overlap between outer cells and neighbors to start
                foreach (HexCoord nh in start.Neighbors())
                {
                    if (eligibleList.Contains(nh) && !IsMoveGapJumping(start, start, nh))
                        eligibleListMod.Add(nh);
                }
                RemoveUnreachableHexes(eligibleListMod);                //Next remove unreachable locations.
                break;

            case UnitType.Beetle:
                //Beetles move one space, but can also move on top of other pieces
                //No restrictions on unreachable hexes
                foreach (HexCoord nh in start.Neighbors())
                {
                    if (beetleDict.ContainsKey(start))
                    {
                        if (beetleDict[start] > 0)      //If this is a beetle moving from on top of the hive, all neighbors will be eligible
                        {
                            eligibleListMod.Add(nh);
                        }

                        else if (eligibleList.Contains(nh) && !IsMoveGapJumping(start, start, nh))  //Add all unnoccupied neighbors that are eligible
                        {
                            eligibleListMod.Add(nh);
                        }
                        else if (occupiedList.Contains(nh))
                        {
                                eligibleListMod.Add(nh);    //Add all occupied neighbors
                        }
                    }
                    //Might not need to repeat these
                    else if (eligibleList.Contains(nh) && !IsMoveGapJumping(start, start, nh))  //Add all unnoccupied neighbors that are eligible
                    {
                        eligibleListMod.Add(nh);

                        if (occupiedList.Contains(nh))
                            eligibleListMod.Add(nh);    //Add all occupied neighbors
                    }
                }
                break;

            case UnitType.Spider:
                //Spiders move exactly 3 spaces following the outer edge of the hive
                //Use outer hex list as a starting point. All outer hexes at exactly 3 spaces from starting point should be eligible
                List<HexCoord> outerHexes = GetOuterHexes(start);

                List<HexCoord> iterList = new List<HexCoord>();
                List<HexCoord> firstSpaces = new List<HexCoord>();
                List<HexCoord> secondSpaces = new List<HexCoord>();
                List<HexCoord> thirdSpaces = new List<HexCoord>();

                for (int i = 1; i < 4; i++)
                {
                    switch (i)
                    {
                        case 1:    //For the first move check neighbors of the start hex
                            iterList.Add(start);
                            break;
                        case 2:     //For the second move check neighbors of each eligible first move space
                            iterList = new List<HexCoord>(firstSpaces);

                            break;
                        case 3:     //For the third move check neighbors of each eligible second move space
                            iterList = new List<HexCoord>(secondSpaces);
                            break;
                    }

                    foreach (HexCoord hex in iterList)
                    {

                        foreach (HexCoord nh in hex.Neighbors())          //First find occupied neighbors
                        {
                            //space must be an outer hex and reachable and the move must not be jumping a gap
                            if (outerHexes.Contains(nh) && !IsHexUnreachable(nh) && !IsMoveGapJumping(start,hex,nh))
                            {
                                switch (i)
                                {
                                    case 1:
                                        firstSpaces.Add(nh);
                                        break;
                                    case 2:
                                        secondSpaces.Add(nh);
                                        break;
                                    case 3:
                                        thirdSpaces.Add(nh);
                                        break;
                                }
                            }
                        }
                    }

                }

                eligibleListMod = new List<HexCoord>(thirdSpaces);      //All eligible third spaces are the full eligible list
                //Remove all first spaces and second spaces. This is an attempt to eliminate back tracking.
                //Since backtracking isn't allowed I don't think there's any way that any
                //first space could also be a valid third space. Same reasoning applies to second spaces
                //although I'm not as sure about the second spaces. Needs testing
                foreach (HexCoord spc in firstSpaces)
                    eligibleListMod.Remove(spc);
                foreach (HexCoord spc in secondSpaces)
                    eligibleListMod.Remove(spc);

                break;

            case UnitType.Grasshopper:
                //Grasshopper jumps in a straight line over other pieces
                //No restrictions on unreachable hexes
                int neighborIndex = 0;
                HexCoord option;
                foreach (HexCoord nh in start.Neighbors())          //First find occupied neighbors
                {
                    if (occupiedList.Contains(nh))                  //If direct neighbor is occupied
                    {
                        option = nh;                                //Initialize option
                        bool solutionFound = false;                 //Initialize bool
                        while (!solutionFound)                      //Repeat until solution is found
                        {
                            option = option.Neighbor(neighborIndex);    //Option might be next neighbor in same direction

                            if (!occupiedList.Contains(option))     //Check if occupied.
                            {
                                eligibleListMod.Add(option);        //If not occupied then add to eligible list
                                solutionFound = true;
                            }
                                                                    //If occupied then keep looking in the same direction. Stay in while loop
                        }
                    }
                    neighborIndex++;
                }
                break;

            default:
                eligibleListMod = eligibleList;
                break;

        }

        return eligibleListMod;
    }