Пример #1
0
        public void Update()
        {
            if (loader != null)
            {
                //TODO: calculate loaders position to the current chunk instead of raycast
                Vector2 pixelCoords = new Vector2(loader.position.x, loader.position.z);
                Vector3 hexCoords = HexMath.PixelToHex(pixelCoords.x, pixelCoords.y, Game.World.HexData);
                //Tile(-33,-8) -> Chunk(-3,-1)
                //-33/13 = -2.5 ~= -3, -8/13 = -0.6 ~= -1
                int chunkSize = Game.GameConfig.chunkSize;
                float x = Mathf.Round(hexCoords.x / chunkSize);
                float z = Mathf.Round(hexCoords.y / chunkSize);
                float y = Mathf.Round(hexCoords.z / chunkSize);
                Vector3 chunkCoords = new Vector3(x, y, z);
                Debug.Log(chunkCoords);
                /*if (Game.World.Chunks.ContainsKey(chunkCoords))
                {
                    Debug.Log("Exists");
                    ChangeChunk(chunkCoords);
                    //currentChunk = Game.World.Chunks[chunkCoords];
                    //Game.ThreadQueuer.StartThreadedFunction(ManageChunks);
                }*/
                ChangeChunk(chunkCoords);
            }

            UpdateChunks();
        }
Пример #2
0
    public bool CheckNeighbors()
    {
        int     isPopulated  = 0;
        int     isValid      = 0;
        Vector3 cubePosition = HexMath.AxialToCube(HexMath.PixelToHex(transform.position));

        RaycastHit hit;
        int        direction;

        for (int i = 0; i < 6; i++)
        {
            if (Physics.Raycast(HexMath.HexToPixel(HexMath.CubeToAxial(cubePosition + HexMath.direction[i])) + Vector3.forward, Vector3.back, out hit))
            {
                Hex hex = hit.collider.GetComponent <Hex>();
                if (hex != null)
                {
                    isPopulated++;

                    direction = i + 3;
                    if (direction > 5)
                    {
                        direction -= 6;
                    }

                    if (hex.CheckValidity(direction, fieldType[i]))
                    {
                        isValid++;
                    }
                }
            }
        }

        return((isPopulated != 0) && (isPopulated == isValid));
    }
        public HashSet <IHexagon> GetTargetsInRange(IHexagon start, int range)
        {
            Queue <IHexagon>   hexQueue       = new Queue <IHexagon>();
            HashSet <IHexagon> visited        = new HashSet <IHexagon>();
            HashSet <IHexagon> targetsInRange = new HashSet <IHexagon>();


            hexQueue.Enqueue(start);
            while (hexQueue.Count != 0)
            {
                IHexagon currentHex = hexQueue.Dequeue();

                if (currentHex.MyHexMap.IsOccupied())
                {
                    if (currentHex.Contents.MyHasTurn != null)
                    {
                        targetsInRange.Add(currentHex);
                    }
                }

                foreach (IHexagon neighbour in currentHex.MyHexMap.Neighbours)
                {
                    if (HexMath.FindDistance(start, neighbour) <= range && !visited.Contains(neighbour))
                    {
                        hexQueue.Enqueue(neighbour);
                        visited.Add(neighbour);
                    }
                }
            }

            //algorithm would return the attacker as a target otherwise
            targetsInRange.Remove(start);

            return(targetsInRange);
        }
    // Neighbor Test Helper
    void NeighborTestHelper(int radius)
    {
        int neighborCount = 1;

        for (int c = 0; c <= radius; c++)
        {
            neighborCount += c * 6;
        }

        Tilemap           tilemap       = GameObject.FindGameObjectWithTag("testTilemap").GetComponent <Tilemap>();
        List <Vector3Int> neighborTiles = new List <Vector3Int>();

        neighborTiles = HexMath.OddrRange(new Vector3Int(0, 0, 0), radius);
        Dictionary <string, int> neighborTestDict = new Dictionary <string, int>();

        Assert.AreEqual(neighborTiles.Count, neighborCount);

        for (int i = 0; i < neighborTiles.Count; i++)
        {
            if (neighborTestDict.ContainsKey(tilemap.GetTile(neighborTiles[i]).name))
            {
                neighborTestDict[tilemap.GetTile(neighborTiles[i]).name]++;
            }
            else
            {
                neighborTestDict.Add(tilemap.GetTile(neighborTiles[i]).name, 1);
            }
        }
        foreach (KeyValuePair <string, int> kvp in neighborTestDict)
        {
            Debug.Log(kvp.Key + ": " + kvp.Value);
        }
    }
Пример #5
0
        public void UpdateActive(Solver solver)
        {
            if (Type > 5 && Type < 12 && Type != solver.MetalLevel)
            {
                return;
            }
            var count = 0;

            for (var i = 0; i < 8; i++)
            {
                //going around
                var x = HexMath.XInDirection(X, Y, i % 6);
                var y = HexMath.YInDirection(Y, i % 6);

                if (solver.Marbles[x * 13 + y] != null)
                {
                    count = 0;
                }
                else
                {
                    count++;
                }
                if (count == 3)
                {
                    solver.ActiveMarbles.Add(this);
                    return;
                }
            }
        }
Пример #6
0
        public void Run()
        {
            //todo move into IEnumerator
            CubeCoords playerCoords = HexMath.Pix2Hex(_player.Transform.localPosition.x, _player.Transform.localPosition.y, HexSize);

            if (_map.LastCoords.x != playerCoords.x || _map.LastCoords.y != playerCoords.y)
            {
                UnrenderRing(_map.LastCoords, Fow + 1);
                RenderRing(playerCoords, Fow);
                _map.LastCoords = playerCoords;
            }

            for (int i = 0; i < _collisionEvents.EntitiesCount; i++)
            {
                CubeCoords coords = HexMath.Pix2Hex(_collisionEvents.Components1[i].ObstacleTransform.position, HexSize);
            }
            for (int i = 0; i < _triggerForegroundEvents.EntitiesCount; i++)
            {
                CubeCoords             coords       = HexMath.Pix2Hex(_triggerForegroundEvents.Components1[i].ObstacleTransform.position, HexSize);
                HexForegroundComponent hexComponent = _map.MapF[coords.x, coords.y];
                switch (hexComponent.ForegroundType)
                {
                case ForegroundTypes.Diamond:
                    _player.Exp += hexComponent.Value;
                    RemoveFore(hexComponent, coords);
                    break;

                default:
                    break;
                }
            }
        }
Пример #7
0
 public void UpdateNeighbours(Solver solver)
 {
     for (var i = 0; i < 6; i++)
     {
         solver.Marbles[HexMath.XInDirection(X, Y, i % 6) * 13 + HexMath.YInDirection(Y, i % 6)]?
         .UpdateActive(solver);
     }
 }
Пример #8
0
    // PLACE WATER
    public void PlaceWater(Vector3Int tileLocation)
    {
        // Set the target tile to be a water tile.
        tilemap.SetTile(tileLocation, groundTileFromName["Water"]);

        // Update groundTiles dictionary.
        groundTiles[tileLocation].ThisTile        = groundTileFromName["Water"];
        groundTiles[tileLocation].DistanceToWater = 0;

        // Get the neighbors.
        List <Vector3Int> neighbors = HexMath.OddrRange(tileLocation, 5);

        foreach (Vector3Int nPosition in neighbors)
        {
            // Look for the tile in the groundTiles dictionary.
            if (groundTiles.ContainsKey(nPosition))
            {
                // Take a look at the neighbor. Look at its NearbyWaterTiles dictionary and DistanceToWater.
                // We want to add this new water into the dictionary and, if DistanceToWater just shrank, update
                // the neighbor to the appropriate tile type.
                int dTW = HexMath.OddrDistance(tileLocation, nPosition);
                if (dTW == 0)
                {
                    // The tile has 0 distance to water, as in, it's looking at itself, so skip this one.
                    continue;
                }
                else if (groundTiles[nPosition].NearbyWaterTiles.ContainsKey(dTW))
                {
                    // This value for dTW exists in the dictionary. Merely add this new water tile to the list.
                    groundTiles[nPosition].NearbyWaterTiles[dTW].Add(tileLocation);
                }
                else
                {
                    // This value for dTW did not exist in the dictionary. Create a new key value pair.
                    groundTiles[nPosition].NearbyWaterTiles.Add(dTW, new List <Vector3Int> {
                        tileLocation
                    });
                }

                // Did the neighbor get closer to water?
                if (dTW < groundTiles[nPosition].DistanceToWater)
                {
                    // dTW changed, so we can update groundTiles dictionary.
                    groundTiles[nPosition].DistanceToWater = dTW;

                    // Which tile should it be, according to its distanceToWater?
                    Tile nTile = GetTileByWaterDistance(dTW, marshDistance, soilDistance);

                    // Start a cooroutine to change the tile.
                    StartCoroutine(DelayedGroundTileChange(nPosition));
                }
            }
        }

        // Last but not least, clear any plant on that tile?
        plantTileManager.ClearPlants(tileLocation);
    }
Пример #9
0
        public void SetSize(Vector2 size)
        {
            this.size = size;
            float xScale   = size.x / HexMath.CalculateHexWidth(referenceHeight);
            float yScale   = size.y / referenceHeight;
            float hexScale = Mathf.Min(xScale, yScale);

            transform.localScale = new Vector3(hexScale, hexScale, 1);
        }
        /**
         * znamy ilość hexów i oczekiwany rozmiar hexów w unitach, obliczamy rozmiar planszy
         */
        private BoardHex BuildCalcBoardSize()
        {
//			this.SetHexNumber (newColNumber, newRowNumber);
//			if (recommendHexHeight <= 0) {
//				Debug.LogError("hexHeight musi być większe od 0");
//			}
//			recommendHexHeight = newHexHeight;
            hexWidth = HexMath.CalculateHexWidth(recommendHexHeight);
            return(this.BuildCalc());
        }
    void DebugHexMath()
    {
        Vector3Int origin     = new Vector3Int(0, 0, 0);
        Vector3Int target     = new Vector3Int(2, 2, 0);
        Vector3Int targetCube = new Vector3Int(1, -3, 2);


        // Distance testing: Oddr then Cube
        Assert.AreEqual(HexMath.OddrDistance(origin, origin), 0);
        Assert.AreEqual(HexMath.OddrDistance(origin, origin + HexMath.CubeDirection(0)), 1);
        Assert.AreEqual(HexMath.OddrDistance(origin, origin + HexMath.CubeDirection(0) * 2), 2);
        Assert.AreEqual(HexMath.OddrDistance(origin, target), 3);
        Assert.AreEqual(HexMath.OddrDistance(origin, target + HexMath.CubeDirection(0)), 2);
        Assert.AreEqual(HexMath.OddrDistance(origin, new Vector3Int(-6, -6, 0)), 9);

        Assert.AreEqual(HexMath.CubeDistance(origin, origin), 0);
        Assert.AreEqual(HexMath.CubeDistance(origin, origin + HexMath.CubeDirection(0) * 2), 2);
        Assert.AreEqual(HexMath.CubeDistance(origin, new Vector3Int(0, 0, 0)), 0);
        Assert.AreEqual(HexMath.CubeDistance(origin, targetCube), 3);
        Assert.AreEqual(HexMath.CubeDistance(origin, target + HexMath.CubeDirection(0)), 2);
        Assert.AreEqual(HexMath.CubeDistance(origin, new Vector3Int(-1, 4, -3)), 4);

        // Cube - Hex conversion testing.
        Vector3Int Hex  = new Vector3Int(1, 1, 0);
        Vector3Int Cube = new Vector3Int(1, -2, 1);

        Assert.AreEqual(Hex, HexMath.CubeToOddr(Cube));
        Assert.AreEqual(Cube, HexMath.OddrToCube(Hex));

        Hex  = new Vector3Int(-2, -2, 0);
        Cube = new Vector3Int(-1, 3, -2);
        Assert.AreEqual(Hex, HexMath.CubeToOddr(Cube));
        Assert.AreEqual(Cube, HexMath.OddrToCube(Hex));

        Hex  = new Vector3Int(1, -2, 0);
        Cube = new Vector3Int(2, 0, -2);
        Assert.AreEqual(Hex, HexMath.CubeToOddr(Cube));
        Assert.AreEqual(Cube, HexMath.OddrToCube(Hex));

        Hex  = new Vector3Int(-2, 2, 0);
        Cube = new Vector3Int(-3, 1, 2);
        Assert.AreEqual(Hex, HexMath.CubeToOddr(Cube));
        Assert.AreEqual(Cube, HexMath.OddrToCube(Hex));

        /* Neighbor Testing: Testing around Origin: (0, 0, 0).
         *  - Radius 0. It's a marsh, so a neighbor test of radius 0 should simply return one marsh.
         *  - Radius 1. Should add 6 soil tiles and count equal 7
         *  - Radius 2. Should add 12 barren tiles and count equal 19.
         *  No tiles should be water for this setup.
         */
        NeighborTestHelper(0);
        NeighborTestHelper(1);
        NeighborTestHelper(2);
        NeighborTestHelper(3);
    }
Пример #12
0
    // REMOVE WATER
    public void RemoveWater(Vector3Int tileLocation)
    {
        // Set the target tile to be a marsh tile. (OR WHATEVER REMOVED WATER TURNS INTO)
        tilemap.SetTile(tileLocation, groundTileFromName["Marsh"]);
        // Update groundTiles dictionary.
        groundTiles[tileLocation].ThisTile = groundTileFromName["Marsh"];

        // Get the neighbors.
        List <Vector3Int> neighbors = HexMath.OddrRange(tileLocation, 5);

        foreach (Vector3Int nPosition in neighbors)
        {
            // Look for the tile in the groundTiles dictionary.
            if (groundTiles.ContainsKey(nPosition))
            {
                // Take a look at the neighbor. Look at its NearbyWaterTiles dictionary and DistanceToWater.
                // We want to remove this water from the dictionary and, if DistanceToWater just rose, update
                // the neighbor to the appropriate tile type.
                int dTW = HexMath.OddrDistance(tileLocation, nPosition);
                if (groundTiles[nPosition].NearbyWaterTiles.ContainsKey(dTW))
                {
                    // This value for dTW exists in the dictionary.
                    if (groundTiles[nPosition].NearbyWaterTiles[dTW].Count >= 2)
                    {
                        // Now if it's the not final item in for this key, just remove it from the list.
                        groundTiles[nPosition].NearbyWaterTiles[dTW].Remove(tileLocation);
                    }
                    else
                    {
                        // Otherwise, the list of water tiles at this exact dTW was only this tile.
                        // Therefore, remove the key value pair from the NearbyWaterTiles dictionary.
                        groundTiles[nPosition].NearbyWaterTiles.Remove(dTW);
                    }
                }
                else
                {
                    // SOMETHING HAS GONE TERRIBLY WRONG: This was a water tile and was within the radius of
                    // influence of this neighbor, yet doesn't show up in the neighbors NearbyWaterTiles?????
                    Debug.Log("Something has gone wrong, removed water tile, at " + tileLocation + " not found" +
                              " in neighbor's near by water tiles, at " + nPosition);
                }

                // Did the neighbor get further from water?
                dTW = GetDistanceToWater(nPosition, groundTiles[nPosition].NearbyWaterTiles);
                if (dTW != groundTiles[nPosition].DistanceToWater)
                {
                    // dTW changed, so we can update groundTiles dictionary.
                    groundTiles[nPosition].DistanceToWater = dTW;

                    // Start a cooroutine to change the tile.
                    StartCoroutine(DelayedGroundTileChange(nPosition));
                }
            }
        }
    }
Пример #13
0
        private void RenderHexForeground(CubeCoords coords)
        {
            if (!_map.MapF.ExistAt(coords) || _map.MapF[coords.x, coords.y].IsNew)
            {
                return;
            }
            HexForegroundComponent foregroundHexComponent = _map.MapF[coords.x, coords.y];

            if (foregroundHexComponent.ForegroundType == ForegroundTypes.Empty)
            {
                return;
            }
            if (foregroundHexComponent.Parent != null)
            {
                return;                                                    //_poolForeground.Recycle(foregroundHexComponent.Parent);
            }
            foregroundHexComponent.Parent = _map.PoolF.Get();
            foregroundHexComponent.Parent.PoolTransform.localPosition = HexMath.Hex2Pix(coords, HexSize);
            switch (foregroundHexComponent.ForegroundType)
            {
            case ForegroundTypes.Empty:
                foregroundHexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = null;
                foregroundHexComponent.Parent.PoolTransform.GetComponent <Collider2D>().enabled    = false;
                return;

            case ForegroundTypes.Enemy:
                foregroundHexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = Enemy;
                foregroundHexComponent.Parent.PoolTransform.GetComponent <Collider2D>().enabled    = true;
                foregroundHexComponent.Parent.PoolTransform.GetComponent <Collider2D>().isTrigger  = false;
                break;

            case ForegroundTypes.Obstacle:
                foregroundHexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = Obstacle;
                foregroundHexComponent.Parent.PoolTransform.GetComponent <Collider2D>().enabled    = true;
                foregroundHexComponent.Parent.PoolTransform.GetComponent <Collider2D>().isTrigger  = false;
                break;

            case ForegroundTypes.Diamond:
                foregroundHexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = Diamond;
                foregroundHexComponent.Parent.PoolTransform.GetComponent <Collider2D>().enabled    = true;
                foregroundHexComponent.Parent.PoolTransform.GetComponent <Collider2D>().isTrigger  = true;
                break;

            case ForegroundTypes.Spawn:
                //spawn point, dunno why
                foregroundHexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = null;
                foregroundHexComponent.Parent.PoolTransform.GetComponent <Collider2D>().enabled    = false;
                break;

            default:
                throw new Exception("Null object type");
            }
            foregroundHexComponent.Parent.PoolTransform.gameObject.SetActive(true);
        }
Пример #14
0
        private int colNumber, rowNumber; //colNumber-x rowNumber-y

        /**
         * metoda pozwala przeliczyć rozmiar całej planszy
         */
        public void Recalculate()
        {
//			int colNumber = Mathf.Abs (colMinCoordinate) + Mathf.Abs (colMaxCoordinate) + 1;//+1 ponieważ jakby narysować to na wykresie to w zakres wchodzi też ostatnia wartość jako pełna
//			int rowNumber = Mathf.Abs (rowMinCoordinate) + Mathf.Abs (rowMaxCoordinate) + 1;//+1 ponieważ jakby narysować to na wykresie to w zakres wchodzi też ostatnia wartość jako pełna
            if (rowNumber > 1 && symmetricHorizontal == false)               //jak symmetricHorizontal true to nie ma przesunięcia wynikającego z połowy hexa na szerokość
            {
                this.size = new Vector2(HexMath.CalculateMultiRowWidth(this.hexSize.x, colNumber), HexMath.CalculateColumnHeight(this.hexSize.y, rowNumber));
            }
            else
            {
                this.size = new Vector2(HexMath.CalculateRowWidth(this.hexSize.x, colNumber), HexMath.CalculateColumnHeight(this.hexSize.y, rowNumber));
            }
        }
Пример #15
0
        /**
         * zwraca listę sąsiednich hexów, gdy range 1 to zwraca tylko pierwsze sąsiedztwo, gdy range 2, to kolejny pierścien dodatkowo
         */
        public List <HexField> GetNeighbors(Vector3 centerCoordinates, int range = 1)
        {
            List <HexField> list            = new List <HexField>();
            List <Vector3>  coordinatesList = HexMath.GetRange(centerCoordinates, range, 0);           //by pominąć kliknięty hex i zwrócić sąsiedztwo

            foreach (Vector3 neigborCoordinates in coordinatesList)
            {
                HexField hex = this.GetHex(neigborCoordinates);
                if (hex != null)
                {
                    list.Add(hex);
                }
            }
            return(list);
        }
Пример #16
0
        private void UnrenderRing(CubeCoords playerCoords, int radius)
        {
            CubeCoords coords = new CubeCoords(playerCoords.x, playerCoords.y + radius);

            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < radius; j++)
                {
                    coords.x += HexMath.Directions[i, 0];
                    coords.y += HexMath.Directions[i, 1];
                    if (HexMath.HexDistance(playerCoords.x, playerCoords.y, coords.x, coords.y) >= Fow)
                    {
                        HideHex(coords);
                    }
                }
            }
        }
Пример #17
0
    // Update is called once per frame
    void Update()
    {
        if (pointer != null)
        {
            Vector3 position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            position = HexMath.HexToPixel(HexMath.PixelToHex(position));
            pointer.transform.position = position;
            if (Input.GetMouseButtonDown(0) && pointer.CheckNeighbors())
            {
                pointer.EndDrag();
                pointer = null;

                pointer = InstantiateHex();
                pointer.BeginDrag();
            }
        }
    }
Пример #18
0
        public void find_straight_distance()
        {
            GameObject    gameObject    = new GameObject();
            MapGeneration mapGeneration = gameObject.AddComponent <MapGeneration>();

            mapGeneration.HexagonPrefab = new GameObject();
            mapGeneration.MapRadius     = 10;

            mapGeneration.HexDict = new Dictionary <Vector3Int, IHexagon>();
            mapGeneration.GenerateMap();
            mapGeneration.UpdateHexNeighbours();

            IHexagon start_hex = mapGeneration.HexDict[new Vector3Int(0, 0, 0)];
            IHexagon end_hex   = mapGeneration.HexDict[new Vector3Int(0, -4, 4)];


            int distance = 4;

            Assert.AreEqual(distance, HexMath.FindDistance(start_hex, end_hex));
        }
Пример #19
0
        public void RenderHexBackground(CubeCoords coords)
        {
            if (!_map.MapB.ExistAt(coords) || _map.MapB[coords.x, coords.y].IsNew)
            {
                MapGenRandomNeighbours.GenerateHex(coords, _map.MapB, _map.MapF);
            }
            HexBackgroundComponent hexComponent = _map.MapB[coords.x, coords.y];

            if (hexComponent.Parent != null)
            {
                return;                                          //_poolBackground.Recycle(hexComponent.Parent);
            }
            hexComponent.Parent = _map.PoolB.Get();
            hexComponent.Parent.PoolTransform.localPosition = HexMath.Hex2Pix(coords, HexSize);
            switch (hexComponent.BackgroundType)
            {
            case BackroundTypes.Grass:
                hexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = Grass;
                hexComponent.SpeedDown = 1;
                break;

            case BackroundTypes.Water:
                hexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = Water;
                hexComponent.SpeedDown = 0.1f;
                break;

            case BackroundTypes.Swamp:
                hexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = Swamp;
                hexComponent.SpeedDown = 0.02f;
                break;

            case BackroundTypes.Forest:
                hexComponent.Parent.PoolTransform.GetComponent <SpriteRenderer>().sprite = Forest;
                hexComponent.SpeedDown = 0.5f;
                break;

            default:
                throw new Exception("Null ground type");
            }
            hexComponent.Parent.PoolTransform.gameObject.SetActive(true);
        }
Пример #20
0
    public Dictionary <int, List <Vector3Int> > GetNearbyWaterTiles(Vector3Int tilePos, Tilemap tilemap, int soilDistance)
    {
        Dictionary <int, List <Vector3Int> > result = new Dictionary <int, List <Vector3Int> >();

        // Use HexMath to get list of nearbyTiles.
        List <Vector3Int> neighborPositions = HexMath.OddrRange(tilePos, soilDistance);

        // For each neighborPosition, check the tile there, looking out for water tiles.
        foreach (Vector3Int nPos in neighborPositions)
        {
            // Is there even a tile here?
            if (!tilemap.HasTile(nPos))
            {
                continue;
            }

            // Is this tile water?
            if (tilemap.GetTile <Tile>(nPos).name.Equals("Water", System.StringComparison.Ordinal))
            {
                // Get the distance from this tile to the water tile.
                int distanceToWater = HexMath.OddrDistance(tilePos, nPos);

                // If the result dictionary has an entry for this distance, add nPos to its value's list.
                if (result.ContainsKey(distanceToWater))
                {
                    result[distanceToWater].Add(nPos);
                }
                // Otherwise, the result dictionary has no entry for this distance yet, so make one.
                else
                {
                    result.Add(distanceToWater, new List <Vector3Int> {
                        nPos
                    });
                }
            }
        }

        return(result);
    }
        /**
         * znamy ilość hexów i rozmiar planszy w unitach. Odpowiada to trybowi FIXED_BOARD_CAL_HEXSIZE
         */
        private BoardHex BuildCalcHexSize()
        {
//			this.SetHexNumber (newColNumber, newRowNumber);
//			if (newRecommendWidth <= 0 || newRecommendHeight <= 0) {
//				Debug.LogError("boardUnitWidth i boardUnitHeight muszą być większe od 0");
//			}
//			recommendSize.x = newRecommendWidth;
//			recommendSize.y = newRecommendHeight;
            float bestHexWidth  = HexMath.CalculateHexWidthInRow(recommendSize.x, colNumber);
            float bestHexHeight = HexMath.CalculateHexHeightInColumn(recommendSize.y, rowNumber);

            hexWidth = HexMath.CalculateHexWidth(bestHexHeight);
            if (hexWidth > bestHexWidth)               //szerokość obliczona z bestHexHeight jest za duża, przyjmujemy więc bestHexWidth jako referencję i obliczamy
            {
                hexWidth           = bestHexWidth;
                recommendHexHeight = HexMath.CalculateHexHeight(hexWidth);
            }
            else                 //prawidłowo obliczona została szerokość
            {
                recommendHexHeight = bestHexHeight;
            }
            return(this.BuildCalc());
        }
Пример #22
0
    void Start()
    {
        neighbors = new int[6, 2] {
            { 0, 1 },
            { 1, 0 },
            { 1, -1 },
            { 0, -1 },
            { -1, 0 },
            { -1, 1 }
        };


        gameController = GameObject.FindGameObjectWithTag("GameController");
        hexMath        = gameController.GetComponent <HexMath>(); // Takes the HexMath script from the Game Control
        boardSize      = new int[gameController.GetComponent <BoardController>().boardsize[0], gameController.GetComponent <BoardController>().boardsize[1]];

        turn = 0;
        setUnitParameters();
        hasDied          = false;
        speed            = 0.12f;
        world_position   = transform.position;
        actionController = GetComponent <ActionController>();
    }
    // Get Tendrils: There are 18 unique tendrils that form using a given tile as a base, not including the
    // tendrils that are also considered clusters.
    private static List <List <Vector3Int> > GetTendrils(Vector3Int baseTilePosition)
    {
        List <List <Vector3Int> > tileTendrils = new List <List <Vector3Int> >();

        // The for loop represents the 6 possible tiles that surround the base tile.
        for (int i = 0; i < 6; i++)
        {
            // Add the center tile since it will be part of every tendril.
            List <Vector3Int> tendril = new List <Vector3Int>();
            tendril.Add(baseTilePosition);

            // Add this loop's tile to this tednril, based on its position relative to the base.
            // That is, baseTilePosition + cubeDirections. Of course we have to convert to and from cube coords.
            Vector3Int targetCubePosition = HexMath.cubeDirections[i] + HexMath.OddrToCube(baseTilePosition);
            Vector3Int targetOddrPosition = HexMath.CubeToOddr(targetCubePosition);
            tendril.Add(targetOddrPosition);

            // The third tile slightly is more complicated. It can be in any three directions based on the initial
            // direction, deviating by -1, 0, and +1, and making sure to wrap from -1 to 5.
            for (int d = -1; d <= 1; d++)
            {
                List <Vector3Int> triple = new List <Vector3Int>();

                int newDirection = ((i + d) % 6 + 6) % 6;
                targetCubePosition = HexMath.cubeDirections[newDirection] + HexMath.OddrToCube(baseTilePosition);
                targetOddrPosition = HexMath.CubeToOddr(targetCubePosition);
                triple.Add(targetOddrPosition);
                triple.AddRange(tendril);

                // Now add this tendril of three tiles to the tileTendrils list.
                tileTendrils.Add(triple);
            }
        }

        return(tileTendrils);
    }
    // Get Clusters: There are 15 unique clusters that form around a central tile.
    // This method makes a list of them and returns them.
    private static List <List <Vector3Int> > GetClusters(Vector3Int centerTilePosition)
    {
        List <List <Vector3Int> > tileClusters = new List <List <Vector3Int> >();

        // The outer loop represents the 6 possible tiles that surround the central tile.
        for (int i = 0; i < 6; i++)
        {
            // Add the center tile since it will be part of every cluster.
            List <Vector3Int> cluster = new List <Vector3Int>();
            cluster.Add(centerTilePosition);

            // Add the first outer loop tile of this cluster, based on its position relative to center.
            // That is, centerTilePosition + cubeDirections. Of course we have to convert to and from cube coords.
            Vector3Int targetCubePosition = HexMath.cubeDirections[i] + HexMath.OddrToCube(centerTilePosition);
            Vector3Int targetOddrPosition = HexMath.CubeToOddr(targetCubePosition);
            cluster.Add(targetOddrPosition);

            // The inner loop goes through each unique third tile addition to the group.
            for (int j = i + 1; j < 6; j++)
            {
                List <Vector3Int> triple = new List <Vector3Int>();

                // Add the inner loop tile of this cluster, based on its position relative to center.
                // That is, centerTilePosition + cubeDirections. Of course we have to convert to and from cube coords.
                targetCubePosition = HexMath.cubeDirections[j] + HexMath.OddrToCube(centerTilePosition);
                targetOddrPosition = HexMath.CubeToOddr(targetCubePosition);
                triple.Add(targetOddrPosition);
                triple.AddRange(cluster);

                // Now add this cluster of three tiles to the tileClusters list.
                tileClusters.Add(triple);
            }
        }

        return(tileClusters);
    }
Пример #25
0
 public void Instantiate(HexMath.Cube position)
 {
 }
        /**
         * do rzeczywistej budowy potrzebujemy rozmiar  hexa i ilość hexów, nie potrzebujemy rozmiaru mapy
         */
        private BoardHex BuildCalc()
        {
            if (board.IsReady() == true)               //znaczy że ta plansza jest już zbudowana
            {
                return(board);
            }
            hexPattern.gameObject.SetActive(false);
            float calcHeigh  = HexMath.CalculateColumnHeight(recommendHexHeight, rowNumber);
            float halfHeight = calcHeigh / 2;            //rowNumber / 2;
            float halfWidth  = 0;

            if (rowNumber > 1 && symmetricHorizontal == false)             // jak symmetricHorizontal true to nie ma przesunięcia wynikającego z połowy hexa na szerokość
            {
                halfWidth = HexMath.CalculateMultiRowWidth(hexWidth, colNumber) / 2;
            }
            else
            {
                halfWidth = HexMath.CalculateRowWidth(hexWidth, colNumber) / 2;
            }
            Transform hexObject;

            board.Config(colNumber, rowNumber, new Vector2(hexWidth, recommendHexHeight), isEven, symmetricHorizontal);
            this.listenerList.OnBuildStart(hexPattern, colNumber, rowNumber, new Vector2(hexWidth, recommendHexHeight), isEven, symmetricHorizontal);
            int inverse = 0;             //ponieważ inverse nie jest hexem o y = 0 tylko jest zależny od rowNumber musimy mieć inną wartość inverse

            if (isEven == true && rowNumber % 2 == 1)
            {
                inverse = 0;
            }
            else if (isEven == true && rowNumber % 2 == 0)
            {
                inverse = 1;
            }
            else if (isEven == false && rowNumber % 2 == 1)
            {
                inverse = 1;
            }
            else if (isEven == false && rowNumber % 2 == 0)
            {
                inverse = 0;
            }
            for (int y = rowNumber - 1; y >= 0; y--)
            {
                for (int x = 0; x < colNumber; x++)
                {
                    if (symmetricHorizontal && x == colNumber - 1 && inverse == 0)
                    {
                        break;
                    }
                    Vector3 newCoordinates;
                    if (isEven)
                    {
                        newCoordinates = HexMath.ConvertEvenROffsetToCubeCoordinate(x, y);
                    }
                    else
                    {
                        newCoordinates = HexMath.ConvertOddROffsetToCubeCoordinate(x, y);
                    }
                    bool listenerResult = this.listenerList.OnCreateHexStart(newCoordinates, new Vector2(x, y), (inverse == 1)?true:false);
                    if (listenerResult == false)
                    {
                        continue;
                    }
                    hexObject = (Transform)Instantiate(hexPattern.transform, new Vector3(0, 0, 0), Quaternion.identity);
                    hexObject.gameObject.SetActive(true);
                    hexObject.transform.parent = board.transform;
                    HexField hexComponent = hexObject.GetComponent <HexField> ();
                    hexComponent.Init();
                    hexComponent.SetPosition(new Vector3(hexWidth * x + hexWidth - inverse * 0.5f * hexWidth - halfWidth, -3 * (y) * recommendHexHeight / 4 + halfHeight - recommendHexHeight / 2, 0));
                    hexComponent.SetSize(new Vector2(hexWidth, recommendHexHeight));
                    board.Add(newCoordinates, hexComponent);
                    hexObject.name = "Hex " + hexComponent.GetCoordinates().ToString() + " " + x + " " + y;
                    this.listenerList.OnCreateHexEnd(hexComponent);
                }
                inverse = (inverse == 1)?0:1;              //na wysokość co drugi wiersz ma przesunięcie - w ten sposób to oznaczamy
            }

//			board.SetHexNumber (colNumber, rowNumber);
            board.Recalculate();
            board.SetReady();
            this.listenerList.OnBuildEnd();
            return(board);
        }
Пример #27
0
    void Start()
    {
        // sequence to parse textfile
        string txtFileAsOneLine = mapTextFile.text;

        string[]      oneLine;
        List <string> txtFileAsLines = new List <string>();

        txtFileAsLines.AddRange(txtFileAsOneLine.Split("\n"[0]));
        oneLine = txtFileAsLines[0].Split(" "[0]);

        boardsize[0] = int.Parse(oneLine[0]);
        boardsize[1] = int.Parse(oneLine[1]);

        tileProperties = new int[boardsize[0], boardsize[1]];
        for (int j = 0; j < boardsize[1]; j++)
        {
            oneLine = txtFileAsLines[1 + j].Split(" "[0]);
            for (int i = 0; i < boardsize[0]; i++)
            {
                tileProperties[i, j] = int.Parse(oneLine[i]);
            }
        }

        // sequence to parse textfile. This time for heights
        txtFileAsOneLine = heightTextFile.text;
        txtFileAsLines   = new List <string>();
        txtFileAsLines.AddRange(txtFileAsOneLine.Split("\n"[0]));

        heightProperties = new float[boardsize[0], boardsize[1]];
        for (int j = 0; j < boardsize[1]; j++)
        {
            oneLine = txtFileAsLines[j].Split(" "[0]);
            for (int i = 0; i < boardsize[0]; i++)
            {
                heightProperties[i, j] = float.Parse(oneLine[i]) * 0.1f;
            }
        }

        tileMatrix     = new GameObject[boardsize[0], boardsize[1]];
        unitMatrix     = new GameObject[boardsize[0], boardsize[1]];
        nextStepMatrix = new GameObject[boardsize[0], boardsize[1]];
        hexMath        = gameObject.GetComponent <HexMath>(); // Takes the HexMath script from the Game Control

        // find the camera for the move to camera function
        Camera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent <CameraController>();


        for (int i = 0; i < boardsize[0]; i++) // Generate the X hexagons
        {
            float x = hexMath.matrix2HexX(i);

            for (int j = 0; j < boardsize[1]; j++) // Generate the Y hexagons
            {
                float y = hexMath.matrix2HexY(i, j);

                GameObject hexagon = Instantiate(HexagonTile);
                hexagon.transform.SetParent(transform);                                                               // Puts the tile under TileManager and gives the same transform
                hexagon.transform.localPosition = new Vector3(x, heightProperties[i, j], y);
                hexagon.transform.GetChild(0).transform.position += new Vector3(0, 0.5f - heightProperties[i, j], 0); // first child is undiscovered
                hexagon.GetComponent <HexagonScript>().set(i, j);

                if (tileProperties[i, j] == 0)
                {
                    //empty

                    hexagon.GetComponent <MeshRenderer>().enabled = false;
                    hexagon.GetComponent <MeshCollider>().enabled = false;
                    hexagon.transform.GetChild(0).GetComponent <MeshRenderer>().enabled = false;
                    hexagon.transform.GetChild(1).GetComponent <MeshRenderer>().enabled = false;
                }
                if (tileProperties[i, j] == 2)
                {
                    //mountain
                    GameObject mountain = Instantiate(mountainPrefab);
                    mountain.transform.SetParent(transform); // Puts the tile under TileManager and gives the same transform
                    mountain.transform.localPosition = new Vector3(x, 0, y);
                    hexagon.GetComponent <MeshCollider>().enabled = false;
                    hexagon.GetComponent <MeshRenderer>().enabled = false;
                }

                if (tileProperties[i, j] == 3)
                {
                    //forrest
                    GameObject forrest = Instantiate(forrestPrefab);
                    forrest.transform.SetParent(transform); // Puts the tile under TileManager and gives the same transform
                    forrest.transform.localPosition = new Vector3(x, 0, y);
                }

                // Create pathing ring on it instantly
                GameObject pathing = Instantiate(pathingRing);
                pathing.transform.SetParent(hexagon.transform);
                pathing.transform.localPosition = new Vector3(0, 0, 0.05f);
                pathing.GetComponent <MeshRenderer>().enabled = false;

                tileMatrix[i, j] = hexagon;
            }
        }

        int[] unitLoc = new int[2] {
            0, 0
        };
        // Spawn the first units

        Vector3[] angles =
        {
            new Vector3 {
                x = 0, y = 0, z = 0
            },
            new Vector3 {
                x = 0, y = 60, z = 0
            },
            new Vector3 {
                x = 0, y = 120, z = 0
            },
            new Vector3 {
                x = 0, y = 180, z = 0
            },
            new Vector3 {
                x = 0, y = 240, z = 0
            },
            new Vector3 {
                x = 0, y = 300, z = 0
            }
        };


        //player 1's units
        unitLoc = new int[2] {
            6, 18
        };
        GameObject Unit = Instantiate(Hoplite);

        Unit.GetComponent <UnitController>().set(unitLoc[0], unitLoc[1]);
        Unit.GetComponent <UnitController>().setTileGoal(unitLoc[0], unitLoc[1], 0);
        unitMatrix[unitLoc[0], unitLoc[1]] = Unit;
        Unit.transform.position            = tileMatrix[unitLoc[0], unitLoc[1]].transform.position;
        unitList.Add(Unit);
        Unit.GetComponent <UnitController>().setPlayerID(0);
        Unit.GetComponent <UnitController>().setTeamID(0);
        Unit.transform.eulerAngles = angles[0];

        unitLoc = new int[2] {
            2, 14
        };
        Unit = Instantiate(Hoplite);
        Unit.GetComponent <UnitController>().set(unitLoc[0], unitLoc[1]);
        Unit.GetComponent <UnitController>().setTileGoal(unitLoc[0], unitLoc[1], 0);
        unitMatrix[unitLoc[0], unitLoc[1]] = Unit;
        Unit.transform.position            = tileMatrix[unitLoc[0], unitLoc[1]].transform.position;
        unitList.Add(Unit);
        Unit.GetComponent <UnitController>().setPlayerID(0);
        Unit.GetComponent <UnitController>().setTeamID(0);
        Unit.transform.eulerAngles = angles[5];

        unitLoc = new int[2] {
            6, 6
        };
        Unit = Instantiate(Hoplite);
        Unit.GetComponent <UnitController>().set(unitLoc[0], unitLoc[1]);
        Unit.GetComponent <UnitController>().setTileGoal(unitLoc[0], unitLoc[1], 0);
        unitMatrix[unitLoc[0], unitLoc[1]] = Unit;
        Unit.transform.position            = tileMatrix[unitLoc[0], unitLoc[1]].transform.position;
        unitList.Add(Unit);
        Unit.GetComponent <UnitController>().setPlayerID(0);
        Unit.GetComponent <UnitController>().setTeamID(0);
        Unit.transform.eulerAngles = angles[4];

        //player 2's units
        unitLoc = new int[2] {
            14, 14
        };
        Unit = Instantiate(Hoplite);
        Unit.GetComponent <UnitController>().set(unitLoc[0], unitLoc[1]);
        Unit.GetComponent <UnitController>().setTileGoal(unitLoc[0], unitLoc[1], 0);
        unitMatrix[unitLoc[0], unitLoc[1]] = Unit;
        Unit.transform.position            = tileMatrix[unitLoc[0], unitLoc[1]].transform.position;
        unitList.Add(Unit);
        Unit.GetComponent <UnitController>().setPlayerID(1);
        Unit.GetComponent <UnitController>().setTeamID(1);
        Unit.transform.eulerAngles = angles[1];

        unitLoc = new int[2] {
            18, 6
        };
        Unit = Instantiate(Hoplite);
        Unit.GetComponent <UnitController>().set(unitLoc[0], unitLoc[1]);
        Unit.GetComponent <UnitController>().setTileGoal(unitLoc[0], unitLoc[1], 0);
        unitMatrix[unitLoc[0], unitLoc[1]] = Unit;
        Unit.transform.position            = tileMatrix[unitLoc[0], unitLoc[1]].transform.position;
        unitList.Add(Unit);
        Unit.GetComponent <UnitController>().setPlayerID(1);
        Unit.GetComponent <UnitController>().setTeamID(1);
        Unit.transform.eulerAngles = angles[2];

        unitLoc = new int[2] {
            14, 2
        };
        Unit = Instantiate(Hoplite);
        Unit.GetComponent <UnitController>().set(unitLoc[0], unitLoc[1]);
        Unit.GetComponent <UnitController>().setTileGoal(unitLoc[0], unitLoc[1], 0);
        unitMatrix[unitLoc[0], unitLoc[1]] = Unit;
        Unit.transform.position            = tileMatrix[unitLoc[0], unitLoc[1]].transform.position;
        unitList.Add(Unit);
        Unit.GetComponent <UnitController>().setPlayerID(1);
        Unit.GetComponent <UnitController>().setTeamID(1);
        Unit.transform.eulerAngles = angles[3];

        // Start the timer
        StartCoroutine(TurnTimer()); // Start the turntimer!!!
    }