Пример #1
0
        public MapChangeArgs(MapData map, HexPoint updatedTile)
        {
            _map = map;

            _updatedTiles = new List<HexPoint>();
            _updatedTiles.Add(updatedTile);
        }
Пример #2
0
        public void ZCoordTest(
            [ValueSource("s_AllPoints")] TestHexPoint hexPoint)
        {
            // Arrange
            var point = new HexPoint(hexPoint.x, hexPoint.y);

            // Assert
            Assert.AreEqual(hexPoint.z, point.z);
        }
Пример #3
0
        public void XZCreationTest(
            [ValueSource("s_AllPoints")] TestHexPoint hexPoint)
        {
            // Arrange
            var point = HexPoint.FromXZ(hexPoint.x, hexPoint.z);

            // Assert
            Assert.AreEqual(hexPoint.y, point.y);
        }
Пример #4
0
        //make another type for def

        public Boolean CanMoveTo(HexPoint moveTo)
        {
            //split for maybe sep messages
            //also cant be straight line, need to pathfind to it
            if (MoveableInMoveRange().Contains(moveTo))
            {
                return(true);
            }
            return(false);
        }
Пример #5
0
 public void MoveTo(HexPoint moveTo)
 {
     if (CanMoveTo(moveTo) && ActiveTurnState[APUseType.Movement] > 0 && ActiveTurnState[APUseType.TotalAp] > 0)//should be checked elsewhere for UI reasons
     {
         Location = moveTo;
         ActorHexGrid.UnHighlightAll();
         ActorHexGrid.DebugLines = new List <DebugLine>();
         UseAp(APUseType.Movement);
     }
 }
Пример #6
0
        /// <inheritdoc/>
        public virtual HexCoords GetHexCoords(HexPoint point, HexSize autoScroll)
        {
            // Adjust for origin not as assumed by GetCoordinate().
            var grid = new HexSize((int)(GridSizeF.Width * 2F / 3F), (int)GridSizeF.Height);

            point -= autoScroll + grid - Margin;

            return(HexCoords.NewCanonCoords(GetCoordinate(_matrixX, point),
                                            GetCoordinate(_matrixY, point)));
        }
Пример #7
0
        /*
         *
         * function cube_round(cube):
         * var rx = round(cube.x)
         * var ry = round(cube.y)
         * var rz = round(cube.z)
         *
         * var x_diff = abs(rx - cube.x)
         * var y_diff = abs(ry - cube.y)
         * var z_diff = abs(rz - cube.z)
         *
         * if x_diff > y_diff and x_diff > z_diff:
         * rx = -ry-rz
         * else if y_diff > z_diff:
         * ry = -rx-rz
         * else:
         * rz = -rx-ry
         *
         * return Cube(rx, ry, rz)
         *
         *  function lerp(a, b, t): # for floats
         * return a + (b - a) * t
         *
         * function cube_lerp(a, b, t): # for hexes
         * return Cube(lerp(a.x, b.x, t),
         *      lerp(a.y, b.y, t),
         *      lerp(a.z, b.z, t))
         *
         * function cube_linedraw(a, b):
         * var N = cube_distance(a, b)
         * var results = []
         * for each 0 ≤ i ≤ N:
         * results.append(cube_round(cube_lerp(a, b, 1.0/N * i)))
         * return results
         */
        #region static methods
        public static int HexDistance(HexPoint hex1, HexPoint hex2)
        {
            //https://www.redblobgames.com/grids/hexagons/#range
            //get cube cord third value
            int cubeValHex1 = -hex1.Q - hex1.R;
            int cubeValHex2 = -hex2.Q - hex2.R;

            //return max(abs(a.x - b.x), abs(a.y - b.y), abs(a.z - b.z))
            return(Math.Max(Math.Max(Math.Abs(hex1.Q - hex2.Q), Math.Abs(hex1.R - hex2.R)), Math.Abs(cubeValHex1 - cubeValHex2)));
        }
Пример #8
0
 public List<GlobalObject> this[HexPoint p]
 {
     get
     {
         List<GlobalObject> result = new List<GlobalObject>();
         if (player.position.TheSameAs(p)) result.Add(player);
         foreach (GlobalObject g in gObjects) if (g.position.TheSameAs(p)) result.Add(g);
         return result;
     }
 }
        /// <summary><c>HexCoords</c> for the hex at the screen point, with the given AutoScroll position.</summary>
        /// <param name="this"></param>
        /// <param name="point">Screen point specifying hex to be identified.</param>
        /// <param name="autoScroll">AutoScrollPosition for game-display Panel.</param>
        static HexCoords GetHexCoordsInner(this IHexgrid @this, HexPoint point, HexSize autoScroll)
        {
            // Adjust for origin not as assumed by GetCoordinate().
            var grid = new HexSize((int)(@this.GridSizeF().Width *2F / 3F), (int)@this.GridSizeF().Height);

            point -= autoScroll + grid - @this.Margin;

            return(HexCoords.NewCanonCoords(@this.GetCoordinate(@this.MatrixX(), point),
                                            @this.GetCoordinate(@this.MatrixY(), point)));
        }
Пример #10
0
 public BasicActor(HexPoint location, string name, Dictionary <string, string> actorData, int rotation, bool PC, string moduleName, HexGrid.HexGrid hexGrid)
 {
     Name         = name;
     Location     = location;
     Controllable = PC;
     Rotation     = rotation;
     ModuleName   = moduleName;
     ActorHexGrid = hexGrid;
     AsignActorData(actorData);
 }
Пример #11
0
 /// <summary>
 /// Calculate three possible locations for the road to be placed at placement gamephase
 /// </summary>
 /// <param name="game"></param>
 /// <param name="board"></param>
 /// <param name="townOrCity"></param>
 public RoutePlaces(XmlGame game, BoardVisual board, HexPoint townOrCity)
 {
     // Add each side to children
     foreach (HexSide side in townOrCity.GetNeighbourSides)
     {
         Point2D newPoint = board.CalculatePosition(side);
         HexSideVisual newHexSide = new HexSideVisual(newPoint, side);
         Children.Add(newHexSide);
     }
 }
Пример #12
0
 public float this[HexPoint pt]
 {
     get
     {
         return _data[pt.X, pt.Y];
     }
     set
     {
         _data[pt.X, pt.Y] = value;
     }
 }
Пример #13
0
        public bool IsLocalMaximum(HexPoint pt)
        {
            bool localMaximum = this[pt] > 0;

            // local maximum
            foreach (HexPoint pts in pt.Neighbors)
                if (MainWindow.Game.Map.IsValid(pts))
                    localMaximum &= (this[pt] >= this[pts]);

            return localMaximum;
        }
Пример #14
0
 public static void DrawLine(HexPoint a, HexPoint b, ref HexPoint[] output)
 {
     output = CoordinateSystem.PointsBetweenHexPoints(a, b);
     foreach (HexPoint p in output)
     {
         if (GlobalGameManager.instance.Map[p].CurrentState != HexStates.Highlighted)
         {
             GlobalGameManager.instance.Map[p].Highlight(true);
         }
     }
 }
Пример #15
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            HexPoint coordinates = new HexPoint(
                property.FindPropertyRelative("x").intValue,
                property.FindPropertyRelative("z").intValue
                );

            label    = new GUIContent("Coordinates");
            position = EditorGUI.PrefixLabel(position, label);
            GUI.Label(position, coordinates.ToString());
        }
Пример #16
0
        public static HexTile GetTileAtDirection(HexPoint point, int direction)
        {
            if (board == null)
            {
                return(null);
            }

            HexPoint targetPoint = point + directions[direction];

            return(board.GetTile(targetPoint) != null?board.GetTile(targetPoint) : null);
        }
Пример #17
0
 public void Apply(HexPoint hexPoint, int value)
 {
     for (int x = 0; x < _width; ++x)
     {
         for (int y = 0; y < _height; ++y)
         {
             int dist = HexPoint.GetDistance(hexPoint.X, hexPoint.Y, x, y);
             this[x, y] += value / (float)Math.Pow(2, dist);
         }
     }
 }
Пример #18
0
 public static void CreateRange(HexPoint center, int rangeDistance, ref HexPoint[] range)
 {
     range = CoordinateSystem.CreateRings(center, rangeDistance);
     foreach (HexPoint p in range)
     {
         if (GlobalGameManager.instance.Map[p].CurrentState != HexStates.Highlighted)
         {
             GlobalGameManager.instance.Map[p].Highlight(true);
         }
     }
 }
Пример #19
0
    public void SetLink(HexPoint a, HexPoint b)
    {
        linkedHexpoint[0] = a;
        linkedHexpoint[1] = b;

        gameObject.name = "Edge between: " + a.name + ", " + b.name;

        SetPositionInWorldCoordinate();

        UpdateLink();
    }
Пример #20
0
    private HexPoint GetCurrentHexPoint(Vector3 worldPos)
    {
        HexPoint hex = CoordinateSystem.pixel_to_flat_hex(new Vector3(worldPos.x, 0, -worldPos.z), out hex);

        if (CoordinateSystem.PointIsOnMap(hex))
        {
            _currentHexTile = GlobalGameManager.instance.Map[hex];
            return(hex);
        }
        return(_currentHexPoint);
    }
Пример #21
0
    private void Start()
    {
        _tileContainer = _tileContainerData;
        min            = CalculateWorldPosition(Vector3.zero);
        max            = CalculateWorldPosition(new Vector3(Screen.width, Screen.height, 0));

        CoordinateSystem.width = _tileContainer.Layer(TileHeight.zero).meshSizeX;
        HexPoint start = CoordinateSystem.pixel_to_flat_hex(Vector3.zero, out start);

        CreateMap(start, _mapRadius);
        CoordinateSystem.isInitialized = true;
    }
Пример #22
0
        public void Render(Player player, HexPoint selectedHex, List <HexPoint> moves)
        {
            if (Grid == null)
            {
                return;
            }

            foreach (Hex hex in Grid)
            {
                Vector2 renderPos = Layout.HexCorner(hex.Position, 3);
                renderPos.X -= Layout.size / 2f * sqrt3;
                renderPos.Y -= Layout.size / 2f;

                renderPos.X = (float)Math.Floor(renderPos.X);
                renderPos.Y = (float)Math.Floor(renderPos.Y);

                Color mask;

                if (selectedHex == hex.Position)
                {
                    if (moves != null && moves.Contains(hex.Position))
                    {
                        mask = Color.FromArgb(80, 0, 100, 0);
                    }
                    else
                    {
                        mask = Color.FromArgb(50, Color.Black);
                    }
                }
                else if (moves != null && moves.Contains(hex.Position))
                {
                    mask = Color.FromArgb(80, 0, 200, 0);
                }
                else
                {
                    mask = Color.Transparent;
                }

                RenderHex(hex.Position, hex.GetTypes(Data), Layout, Color.White, frameCount, Grid);

                if (mask.A > 0)
                {
                    TextureRenderer.DrawHex(Textures.Get("Hex\\Mask"), hex.Position, Layout, Vector2.One * Layout.size, mask, null);
                }

                if (hex.Position == player.Position)
                {
                    TextureRenderer.DrawHex(Textures.Get("Player"), hex.Position, Layout, Vector2.One * Layout.size, player.Color, null);
                }
            }

            frameCount++;
        }
Пример #23
0
    protected Edge FindEdgeBetween(HexPoint a, HexPoint b)
    {
        for (int i = 0; i < edges.Count; i++)
        {
            if (edges[i].IsLinkBetween(a, b))
            {
                return(edges[i]);
            }
        }

        return(null);
    }
Пример #24
0
        public override long Part1(string input)
        {
            black = new HashSet <HexPoint>();
            var start = new HexPoint(0, 0, 0);

            foreach (var line in Utils.splitLines(input))
            {
                var line2 = line.Replace("se", "a").Replace("sw", "b").Replace("ne", "c").Replace("nw", "d");
                var pos   = start;

                foreach (var move in line2)
                {
                    switch (move)
                    {
                    case 'e':
                        pos = pos.E();
                        break;

                    case 'w':
                        pos = pos.W();
                        break;

                    case 'a':
                        pos = pos.SE();
                        break;

                    case 'b':
                        pos = pos.SW();
                        break;

                    case 'c':
                        pos = pos.NE();
                        break;

                    case 'd':
                        pos = pos.NW();
                        break;
                    }
                }

                if (black.Contains(pos))
                {
                    black.Remove(pos);
                }
                else
                {
                    black.Add(pos);
                }
            }

            return(black.Count);
        }
Пример #25
0
 public HexTile(GameObject worldObject, HexPoint point, TileData data)
 {
     tileType             = TileType.Default;
     _currentState        = HexStates.Idle;
     _q                   = (int)point.q;
     _r                   = (int)point.r;
     _worldtransform      = worldObject.transform;
     _defaultPosition     = _worldtransform.position;
     _renderer            = worldObject.GetComponentInChildren <MeshRenderer>();
     _material            = _renderer.material;
     _highlightedPosition = _defaultPosition + Vector3.up * 0.1f;
     highestPoint         = _defaultPosition + Vector3.up * (data.meshSizeY - MapGenerator.DefaultTile.meshSizeY / 2);
 }
Пример #26
0
        public HexPoint SelectedHex(Vector2 screenCordinates)
        {
            var R             = (int)Math.Round((2.0f / 3.0f * screenCordinates.Y) / HexYSize);
            var Q             = (int)Math.Round(((Math.Sqrt(3) / 3 * screenCordinates.X) - (1.0f / 3.0f * screenCordinates.Y)) / HexXSize);
            var possiblePoint = new HexPoint(R, Q);
            var inGrid        = HexStorage.Any(h => h.Key.Equals(possiblePoint));

            if (!inGrid)
            {
                return(null);
            }
            return(possiblePoint);
        }
Пример #27
0
 public int RotateToDirectionMoved(HexPoint dir)
 {
     //comments for "base" case
     //maybe look at ratios for more fine grained turning -> other things should determine rot later though
     //dont be lazy just draw it out :TODO
     if (dir.Q > 0 && dir.R < 0)//dir.Q == 1 && dir.R == -1
     {
         return(0);
     }
     else if (dir.Q > 0 && dir.R == 0)//dir.Q == 1 && dir.R == 0
     {
         return(1);
     }
     else if (dir.Q == 0 && dir.R > 0)//dir.Q == 0 && dir.R == 1
     {
         return(2);
     }
     else if (dir.Q < 0 && dir.R > 0)//dir.Q == -1 && dir.R == 1
     {
         return(3);
     }
     else if (dir.Q < 0 && dir.R == 0)//dir.Q == -1 && dir.R == 0
     {
         return(4);
     }
     else if (dir.Q == 0 && dir.R < 0)//if (dir.Q == 0 && dir.R == -1)
     {
         return(5);
     }
     else
     {
         if (dir.Q > 0 && dir.R > 0)
         {
             if (dir.Q > dir.R)
             {
                 return(1);
             }
             return(2);
         }
         if (dir.Q < 0 && dir.R < 0)
         {
             if (dir.R > dir.Q)
             {
                 return(4);
             }
             return(5);
         }
     }
     //should never happpen
     return(new Random().Next(6));
 }
Пример #28
0
 public void GoTo(HexPoint _point)
 {
     for (int i = 0; i < MapConstants.height; i++)
     {
         for (int j = 0; j < MapConstants.width; j++)
         {
             if (_point == MapConstants.cells[i, j].coordinates)
             {
                 SetPosition(MapConstants.cells[i, j]);
                 return;
             }
         }
     }
 }
Пример #29
0
        public void Rotate180Test(
            [ValueSource("s_ValidPoints")] TestHexPoint source,
            [ValueSource("s_180RotatedValidPoints")] TestHexPoint expected)
        {
            // Arrange
            var point         = new HexPoint(source.x, source.y);
            var expectedPoint = new HexPoint(expected.x, expected.y);

            // Act
            point = HexPoint.Rotate180(point);

            // Assert
            Assert.AreEqual(expectedPoint, point);
        }
Пример #30
0
    public int Path(Vector2Int startPos, Vector2Int endPos, out HexPoint[] path)
    {
        Vector2Int delta          = endPos - startPos; // go correct direction
        int        pathLength     = 0;
        int        diagonalLength = 0;

        if (delta.x * delta.y > 0)
        {
            diagonalLength = Mathf.Abs(delta.x) + Mathf.Abs(delta.y) - Mathf.Abs(delta.x - delta.y);
            diagonalLength = (int)(diagonalLength * 0.5f);

            pathLength = Mathf.Abs(delta.x) + Mathf.Abs(delta.y) - diagonalLength;
        }
        else
        {
            pathLength = Mathf.Abs(delta.x) + Mathf.Abs(delta.y);
        }

        path    = new HexPoint[pathLength + 1];
        path[0] = GetPoint(startPos);
        int i = 1;


        // move in diagonal
        while (i <= diagonalLength)
        {
            path[i] = GetPoint(path[i - 1].positionInBoard + ExdMath.DIRECTION_SIX[2] * (int)Mathf.Sign(delta.x));
            i++;
        }

        // move in x or y axis
        if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
        {
            while (i <= pathLength)
            {
                path[i] = GetPoint(path[i - 1].positionInBoard + ExdMath.DIRECTION_SIX[1] * (int)Mathf.Sign(delta.x));
                i++;
            }
        }
        else
        {
            while (i <= pathLength)
            {
                path[i] = GetPoint(path[i - 1].positionInBoard + ExdMath.DIRECTION_SIX[3] * (int)Mathf.Sign(delta.y));
                i++;
            }
        }

        return(pathLength);
    }
Пример #31
0
    public bool IsLinkBetween(HexPoint a, HexPoint b)
    {
        if (a == linkedHexpoint[0] && b == linkedHexpoint[1])
        {
            return(true);
        }

        if (a == linkedHexpoint[1] && b == linkedHexpoint[0])
        {
            return(true);
        }

        return(false);
    }
Пример #32
0
        public void ReflectZOffsetTest(
            [ValueSource("s_ValidPoints")] TestHexPoint source,
            [ValueSource("s_OffsetZMirroredValidPoints")] TestHexPoint expected)
        {
            // Arrange
            var point         = new HexPoint(source.x, source.y);
            var expectedPoint = new HexPoint(expected.x, expected.y);

            // Act
            point = HexPoint.ReflectZ(point, 1);

            // Assert
            Assert.AreEqual(expectedPoint, point);
        }
Пример #33
0
 public bool IsCellExist(HexPoint _point)
 {
     for (int i = 0; i < MapConstants.height; i++)
     {
         for (int j = 0; j < MapConstants.width; j++)
         {
             if (_point == MapConstants.cells[i, j].coordinates)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Пример #34
0
        public void DoubleRightRotateTest(
            [Random(-10000, 10000, 5)] int x,
            [Random(-10000, 10000, 5)] int y)
        {
            // Arrange
            var point         = new HexPoint(x, y);
            var expectedPoint = HexPoint.RotateRight(HexPoint.RotateRight(point));

            // Act
            point = HexPoint.RotateRight120(point);

            // Assert
            Assert.AreEqual(expectedPoint, point);
        }
Пример #35
0
        public string RunPart1(IEnumerable <string> testData)
        {
            var input = testData.First().Split(',');

            // Start at home
            var current = new HexPoint(0, 0, 0);

            foreach (var direction in input)
            {
                var point = _actions[direction];
                current = current.AddPoint(point);
            }

            return(current.CalculateDistanceToRoot().ToString());
        }
Пример #36
0
        public void Left120OffsetRotateTest(
            [ValueSource("s_RightOffsetRotatedValidPoints")] TestHexPoint source,
            [ValueSource("s_LeftOffsetRotatedValidPoints")] TestHexPoint expected)
        {
            // Arrange
            var point         = new HexPoint(source.x, source.y);
            var expectedPoint = new HexPoint(expected.x, expected.y);
            var offsetPoint   = new HexPoint(s_OffsetPosition.x, s_OffsetPosition.y);

            // Act
            point = HexPoint.RotateLeft120(point, offsetPoint);

            // Assert
            Assert.AreEqual(expectedPoint, point);
        }
Пример #37
0
        public ForestEntity(HexPoint point)
        {
            if( model == null )
                model = MainApplication.ManagerInstance.Content.Load<Model>("Content\\Models\\forest");

            Point = point;
            Scale = new Vector3(0.01f);
            Rotation = new Vector3(0, (float)(rand.NextDouble() * Math.PI * 2), 0);

            int boneCount = model.Bones.Count;
            boneVisible = Enumerable.Repeat<bool>(true, boneCount).ToArray();

            this.boneTransforms = new Matrix[boneCount];
            model.CopyBoneTransformsTo(this.boneTransforms);

            this.absoluteBoneTransforms = new Matrix[boneCount];
        }
Пример #38
0
 public override BehaviourResult Clicked(RayMeshGeometry3DHitTestResult rayMeshResult, BoardVisual board)
 {
     Road hsv = rayMeshResult.VisualHit as Road;
     if (hsv != null)
     {
         hsv.IsRoadSelected = true;
     }
     BuildPointVisual buildPoint = rayMeshResult.VisualHit as BuildPointVisual;
     if (buildPoint != null)
     {
         //board.Game.PlayerOnTurn.Cities.Add(buildPoint.Location);
         _Location = buildPoint.Location;
         board.SetNeutral();
         ((BuildCityAction)_OriginatingAction).Location = buildPoint.Location;
         return BehaviourResult.Success;
     }
     return BehaviourResult.NoSuccess;
 }
Пример #39
0
        //protected Dictionary<PolicyType, bool> _policies = new Dictionary<PolicyType, bool>();

        public ModellingTile(HexPoint pt)
        {
            _location = pt;

            // init rules
            _systems.Add(RuleType.Citizen, new CitizenRuleSystem(this,500));
            _systems.Add(RuleType.GrowthRate, new GrowthRateRuleSystem(this,1.1));
            _systems.Add(RuleType.Pollution, new PollutionRuleSystem(this, 0.0));
            _systems.Add(RuleType.GDP, new GrossDomesticProduct(this));
            _systems.Add(RuleType.Productivity, new ProductivitySystem(this, 0.0));

            _systems.Add(RuleType.Food, new FoodSystem(this, 0.0));
            _systems.Add(RuleType.CorporateTaxRate, new CorporateTaxRateSystem(this, 0.0));
            _systems.Add(RuleType.Crime, new CrimeSystem(this, 0.0));
            _systems.Add(RuleType.AgricultureLevel, new AgricultureSystem(this, 0.0));
            _systems.Add(RuleType.EnergyCost, new EnergyCostSystem(this));

            _systems.Add(RuleType.Immigration, new ImmigrationRuleSystem(this));
            _systems.Add(RuleType.Poverty, new PovertyRuleSystem(this));

            // people
            _systems.Add(RuleType.LowIncomePeople, new LowIncomePeopleRuleSystem(this));
            _systems.Add(RuleType.MidIncomePeople, new MidIncomePeopleRuleSystem(this));
            _systems.Add(RuleType.HighIncomePeople, new HighIncomePeopleRuleSystem(this));

            // money
            _systems.Add(RuleType.LowIncome, new LowIncomeRuleSystem(this));
            _systems.Add(RuleType.MidIncome, new MidIncomeRuleSystem(this));
            _systems.Add(RuleType.HighIncome, new HighIncomeRuleSystem(this));

            //// Tradition
            //_policies.Add(PolicyType.Aristocracy, false);
            //_policies.Add(PolicyType.Oligarchy, false);
            //_policies.Add(PolicyType.Legalism, false);
            //_policies.Add(PolicyType.LandedElite, false);
            //_policies.Add(PolicyType.Monarchy, false);

            //// Liberty
            //_policies.Add(PolicyType.CollectiveRule, false);
            //_policies.Add(PolicyType.Citizenship, false);
            //_policies.Add(PolicyType.Republic, false);
            //_policies.Add(PolicyType.Representation, false);
            //_policies.Add(PolicyType.Meritocracy, false);
        }
Пример #40
0
        public MapRenderer(Manager manager)
        {
            _manager = manager;

            _baseMesh = new Mesh(manager.GraphicsDevice, "ground");
            _cursorsMesh = new Mesh(manager.GraphicsDevice, "cursors");
            _borderMesh = new Mesh(manager.GraphicsDevice, "cursors");
            _roadMesh = new Mesh(manager.GraphicsDevice, "roads");
            _farmMesh = new Mesh(manager.GraphicsDevice, "farms");
            _riverMesh = new Mesh(manager.GraphicsDevice, "rivers");

            TextureManager.Instance.Device = manager.GraphicsDevice;

            _hiddenMeshContainer = new TiledMeshContainer(manager);

            FogOfWarEnabled = true;

            hMesh = new HexMesh(manager.GraphicsDevice);

            Center = new HexPoint();
        }
Пример #41
0
    public override void Move(HexPoint.HexDirection d)
    {
        base.Move(d);

        foreach (LocalObject c in party) c.fatigue.Add(W.map[position.Shift(d)].type.travelTime * c.hp.Max);

        ground.Clear();
        crafting.Clear();

        foreach (ItemShape s in W.map[position].items) if (W.random.Next(50) <= Sum(Skill.Get("Survival")))	ground.Add(s);

        if (barter != null)
        {
            foreach (Item item in toBuy.Items) if (barter.inventory.CanAdd(item)) barter.inventory.Add(item);
            foreach (Item item in toSell.Items) if (inventory.CanAdd(item)) inventory.Add(item);

            toBuy.Clear();
            toSell.Clear();
            barter = null;
        }

        UpdateVisitedLocations();
    }
Пример #42
0
        public Unit(HexPoint point, AbstractPlayerData player, UnitData data)
        {
            _point = point;
            _player = player;
            _data = data;

            Strength = 10;

            _unitAI = _data.DefaultUnitAI;

            UpdateSpotting();

            InitTransitions();
            InitFormation();

            _entity = new UnitEntity(player, this, _data.ModelName);
            _entity.Point = point;
            _entity.Scale = new Vector3(_data.ModelScale);

            _unitActionBillboard = new BillboardSystem<UnitAction>(MainApplication.Instance.GraphicsDevice, MainApplication.Instance.Content);
            _unitActionBillboard.AddEntity(UnitAction.Idle, Provider.GetAtlas("UnitActionAtlas").GetTexture("Idle"), new Vector2(2, 2));
            _unitActionBillboard.AddEntity(UnitAction.Move, Provider.GetAtlas("UnitActionAtlas").GetTexture("Move"), new Vector2(2, 2));
            _unitActionBillboard.AddEntity(UnitAction.BuildFarm, Provider.GetAtlas("UnitActionAtlas").GetTexture("BuildFarm"), new Vector2(2, 2));
            _unitActionBillboard.AddEntity(UnitAction.BuildRoad, Provider.GetAtlas("UnitActionAtlas").GetTexture("BuildRoad"), new Vector2(2, 2));
            _unitActionBillboard.AddEntity(UnitAction.Found, Provider.GetAtlas("UnitActionAtlas").GetTexture("Found"), new Vector2(2, 2));

            UpdateUnitAction();

            // path mesh
            _pathMesh = new Mesh(MainApplication.Instance.GraphicsDevice, "paths");

            if( TextureManager.Instance.Device == null )
                TextureManager.Instance.Device = MainApplication.Instance.GraphicsDevice;

            TextureManager.Instance.Add("paths", MainApplication.Instance.Content.Load<Texture2D>("Content/Textures/Ground/paths"));
            _pathMesh.LoadContent(MainApplication.Instance.Content);
        }
Пример #43
0
        public City GetCityAt(HexPoint pt)
        {
            foreach (City c in _cities)
                if (c.Point == pt)
                    return c;

            return null;
        }
Пример #44
0
        public Unit GetUnitAt(HexPoint pt)
        {
            foreach (Unit u in _units)
                if (u.Point == pt)
                    return u;

            return null;
        }
Пример #45
0
 public MapControllingArgs(MapData map, HexPoint point, int controller)
 {
     _map = map;
     _tile = point;
     _controller = controller;
 }
Пример #46
0
 public MapSpottingArgs(MapData map, HexPoint point, bool spotting)
 {
     _map = map;
     _tile = point;
     _spotting = spotting;
 }
Пример #47
0
 public City(Point2D point, Color color, HexPoint location)
     : base(point, color)
 {
     Location = location;
     Init();
 }
Пример #48
0
        private bool HasNearPointOrSelf(List<HexPoint> checkList, HexPoint pointToCheck)
        {
            // Check if the list contains the point
            if (checkList.Contains(pointToCheck)) return true;

            // Check if the list contains any of the neightbours
            List<HexPoint> neighbours = pointToCheck.GetNeighbours();
            if (neighbours.Count != 3) Console.WriteLine("whoa");
            foreach (HexPoint neighbour in neighbours)
                if (checkList.Contains(neighbour)) return true;

            // Nope! the list doesnt contains the point or any of its neighbours
            return false;
        }
Пример #49
0
        public void AddCity(HexPoint point)
        {
            // check if this is really possible (controlled by must be -1 or Id)
            if (Map[point].ControlledBy != -1 && Map[point].ControlledBy != Id)
                throw new Exception("This should not have happend, cities can only be build on tiles that are free or controlled by yourself");

            if (!Map[point].Improvements.Contains(road))
                Map[point].Improvements.Add(road);

            string cityName = GetNextCityName();

            City c = new City(point, cityName, this);

            c.IsCapital = _cities.Count == 0;

            GameFacade.getInstance().SendNotification(
                GameNotification.Message,
                NotificationType.FoundCity,
                string.Format(Strings.TXT_KEY_NOTIFICATION_FOUND_CITY, c.Player.Leader.Title, c.Name),
                Civilization,
                MessageFilter.Self | MessageFilter.Friends,
                c);

            c.CityGrowth += delegate(City city, int from, int to)
            {
                GameFacade.getInstance().SendNotification(
                    GameNotification.Message,
                    NotificationType.CityGrowth,
                    string.Format(Strings.TXT_KEY_NOTIFICATION_CITY_GREW, city.Name, c.Player.Leader.Title, to),
                    city.Player.Civilization,
                    MessageFilter.Friends | MessageFilter.Self,
                    city);
            };
            c.CityDecline += delegate(City city, int from, int to)
            {
                GameFacade.getInstance().SendNotification(
                    GameNotification.Message,
                    NotificationType.CityDecline,
                    string.Format(Strings.TXT_KEY_NOTIFICATION_CITY_DECLINE, city.Name, c.Player.Leader.Title, to),
                    city.Player.Civilization,
                    MessageFilter.Friends | MessageFilter.Self,
                    city);
            };
            c.CityBuild += delegate(City city, Building building)
            {
                GameFacade.getInstance().SendNotification(
                    GameNotification.Message,
                    NotificationType.ProducationReady,
                    string.Format(Strings.TXT_KEY_NOTIFICATION_CITY_BUILDING, city.Name, c.Player.Leader.Title, building.Title),
                    city.Player.Civilization,
                    MessageFilter.Self,
                    city);
            };
            c.UnitBuild += delegate(City city, UnitData unit)
            {
                GameFacade.getInstance().SendNotification(
                    GameNotification.Message,
                    NotificationType.ProducationReady,
                    string.Format(Strings.TXT_KEY_NOTIFICATION_CITY_UNIT, city.Name, c.Player.Leader.Title, unit.Title),
                    city.Player.Civilization,
                    MessageFilter.Self,
                    city);
            };

            Map.SetControlled(point, Id, false, 1);

            _cities.Add(c);
        }
Пример #50
0
 public void CenterAt(HexPoint loc)
 {
     if (Map != null && Map.IsValid(loc))
     {
         _mapCenter.X = loc.X;
         _mapCenter.Y = loc.Y;
         _camera.Target = MapData.GetWorldPosition(_mapCenter);
         _mapRenderer.Center = _mapCenter;
     }
 }
Пример #51
0
        private void HandleMouse()
        {
            MouseState mouseState = Mouse.GetState();

            if (mouseState.ScrollWheelValue > _oldMouseState.ScrollWheelValue)
                ZoomIn();
            else if (mouseState.ScrollWheelValue < _oldMouseState.ScrollWheelValue)
                ZoomOut();

            if (mouseState.RightButton == ButtonState.Released && _oldMouseState.RightButton == ButtonState.Pressed)
            {
                City city = MainWindow.Game.GetCityAt(_mapRenderer.Cursor);

                // select unit city
                if (city != null)
                {
                    if (CityOpened != null)
                        CityOpened(city);
                }
            }
            else if (mouseState.LeftButton == ButtonState.Pressed && _oldMouseState.LeftButton == ButtonState.Released)
            {
                _dragStart = _mapRenderer.Cursor;
            }
            else if (mouseState.LeftButton == ButtonState.Released && _oldMouseState.LeftButton == ButtonState.Pressed)
            {
                if (_dragStart != _mapRenderer.Cursor)
                {
                    // drag action
                    Unit unit = MainWindow.Game.GetUnitAt(_dragStart);

                    if (unit != null)
                    {
                        unit.Action = UnitAction.Move;
                        unit.SetTarget(_mapRenderer.Cursor);
                    }
                }
                else
                {
                    Unit unit = MainWindow.Game.GetUnitAt(_mapRenderer.Cursor);

                    // select unit
                    if (unit != null)
                    {
                        if (unit.Player.IsHuman && HumanUnitsSelected != null)
                            HumanUnitsSelected(unit);
                        else if (!unit.Player.IsHuman && EnemyUnitsSelected != null)
                            EnemyUnitsSelected(unit);
                    }
                    else if (UnitsUnselected != null)
                        UnitsUnselected();
                }
            }
          
            _oldMouseState = mouseState;
        }
Пример #52
0
        /// <summary>
        /// Constructs a new movdelvisual with appropriate positions marked where
        /// players can build
        /// </summary>
        /// <param name="b"></param>
        public BuildPlaces(BoardVisual b)
        {
            // Pseudo:
            //
            // By only checking the 4 points on the right (top, top right,
            // lower right, center bottom) points, we can cover the whole
            // board if we just iterate over the hexes in uneven rows
            //
            // 1. Iterate through all hexes in uneven rows
            // 2. Add top center buildpoint, if appropriate
            //  2a. skip the first hex in a row
            // 3. Add top right buildpoint, if appropriate
            //  3a. skip last hex in a row
            // 4. Add lower right buildpoint, if appropriate
            //  4a. skip last hex on the row
            //  4b. Skip if hex is on last row
            // 5. Add center bottom buildpoint, if appropriate
            //  5a. skip last hex on the row
            //  5b. Skip if hex is on last row

            foreach (Hex h in b.Board.Hexes)
            {
                //NoneHexes should not get any build point, so skip them
                //We are only going to iterate over even rows
                if (!(h is NoneHex) && (h.Location.H % 2 != 0))
                {
                    //x offset for positioning the visuals correctly
                    double offsetx = -(b.Board.Width * Hex.Width) / 2;
                    //y offset for positioning the visuals correctly
                    double offsety = -((b.Board.Height * Hex.PartialHeight) + Hex.BottomHeight) / 2;
                    if (h.Location.W != Hex.Width - 1) //omit last hex in row
                    {
                        //0 (point at the top of a hex
                        if (h.Location.W != 0 && // skip if first hex in the row
                            CanBuild(b.Board.Hexes[h.Location.W - 1, h.Location.H - 1]) &&
                            CanBuild(b.Board.Hexes[h.Location.W, h.Location.H - 1]))
                        {
                            //when all three sea hexes, there is no possibility to build
                            if (!(b.Game.Board.Hexes[h.Location.W - 1, h.Location.H - 1] is SeaHex &&
                                b.Game.Board.Hexes[h.Location.W, h.Location.H - 1] is SeaHex &&
                                h is SeaHex))
                            {
                                HexPoint hexPoint = new HexPoint(h.Location, EPointPositionOnHex.TopMiddle);
                                Point2D point = b.CalculatePosition(hexPoint);
                                Children.Add(new BuildPointVisual(point, hexPoint));
                            }
                        }
                        // 1 point at the right top
                        if (h.Location.W != b.Game.Board.Width - 1 && //skip if last hex in a row
                            CanBuild(b.Board.Hexes[h.Location.W, h.Location.H - 1]) &&
                            CanBuild(b.Board.Hexes[h.Location.W + 1, h.Location.H]))
                        {
                            //when all three sea hexes, there is no possibility to build
                            if (!(b.Board.Hexes[h.Location.W, h.Location.H - 1] is SeaHex &&
                                b.Board.Hexes[h.Location.W + 1, h.Location.H] is SeaHex &&
                                h is SeaHex))
                            {
                                HexPoint hexPoint = new HexPoint(h.Location, EPointPositionOnHex.RightTop);
                                Point2D point = b.CalculatePosition(hexPoint);
                                Children.Add(new BuildPointVisual(point, hexPoint));
                            }
                        }
                        if (h.Location.H != Hex.Height - 1) //skip if hex is on last row
                        {
                            // 2 point at the right lower position
                            if (h.Location.W != b.Board.Width - 1 && //skip if last hex in a row (last column)
                                h.Location.H != b.Board.Height - 1 && //skip if hex is on last row
                                CanBuild(b.Board.Hexes[h.Location.W + 1, h.Location.H]) &&
                                CanBuild(b.Board.Hexes[h.Location.W, h.Location.H + 1]))
                            {
                                //when all three sea hexes, there is no possibility to build
                                if (!(b.Board.Hexes[h.Location.W + 1, h.Location.H] is SeaHex &&
                                    b.Board.Hexes[h.Location.W, h.Location.H + 1] is SeaHex &&
                                    h is SeaHex))
                                {
                                    HexPoint hexPoint = new HexPoint(h.Location, EPointPositionOnHex.RightBottom);
                                    Point2D point = b.CalculatePosition(hexPoint);
                                    Children.Add(new BuildPointVisual(point, hexPoint));
                                }
                            }
                            // 3 point at the bottom
                            if (h.Location.H != b.Game.Board.Height - 1 && //skip if hex is on last row
                                h.Location.W != 0 && //skip if first in a row
                                CanBuild(b.Board.Hexes[h.Location.W, h.Location.H + 1]) &&
                                CanBuild(b.Board.Hexes[h.Location.W - 1, h.Location.H + 1]))
                            {
                                //when all three sea hexes, there is no possibility to build
                                if (!(b.Board.Hexes[h.Location.W, h.Location.H + 1] is SeaHex &&
                                    b.Board.Hexes[h.Location.W - 1, h.Location.H + 1] is SeaHex &&
                                    h is SeaHex))
                                {
                                    HexPoint hexPoint = new HexPoint(h.Location, EPointPositionOnHex.BottomMiddle);
                                    Point2D point = b.CalculatePosition(hexPoint);
                                    Children.Add(new BuildPointVisual(point, hexPoint));
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #53
0
 public bool IsInside(HexPoint pt)
 {
     return IsInside(pt.X, pt.Y);
 }
Пример #54
0
        private void SetUpWaterVertices()
        {
            float terrainWidth = 200f;
            float terrainLength = 200f;

            if (MainWindow.Game.Map != null)
            {
                HexPoint topLeft = new HexPoint(0, 0);
                HexPoint bottomRight = new HexPoint(MainWindow.Game.Map.Width, MainWindow.Game.Map.Height);

                Vector3 topLeftPt = MapData.GetWorldPosition(topLeft);
                Vector3 bottomRightPt = MapData.GetWorldPosition(bottomRight);

                terrainWidth = Math.Max( topLeftPt.X, bottomRightPt.X ) + 5f;
                terrainLength = Math.Max(topLeftPt.Z, bottomRightPt.Z) + 5f;
            }

            VertexPositionNormalTexture[] waterVertices = new VertexPositionNormalTexture[6];

            waterVertices[0] = new VertexPositionNormalTexture(new Vector3(0, waterHeight - 1f, 0), Vector3.Up, new Vector2(0, 1));
            waterVertices[2] = new VertexPositionNormalTexture(new Vector3(terrainWidth, waterHeight - 1f, terrainLength), Vector3.Up, new Vector2(1, 0));
            waterVertices[1] = new VertexPositionNormalTexture(new Vector3(0, waterHeight - 1f, terrainLength), Vector3.Up, new Vector2(0, 0));

            waterVertices[3] = new VertexPositionNormalTexture(new Vector3(0, waterHeight - 1f, 0), Vector3.Up, new Vector2(0, 1));
            waterVertices[5] = new VertexPositionNormalTexture(new Vector3(terrainWidth, waterHeight - 1f, 0), Vector3.Up, new Vector2(1, 1));
            waterVertices[4] = new VertexPositionNormalTexture(new Vector3(terrainWidth, waterHeight - 1f, terrainLength), Vector3.Up, new Vector2(1, 0));

            waterVertexBuffer = new VertexBuffer(_dDevice, VertexPositionNormalTexture.VertexDeclaration, waterVertices.Length, BufferUsage.WriteOnly);

            waterVertexBuffer.SetData(waterVertices);

            short[] waterIndexData = new short[6];
            waterIndexData[0] = 0;
            waterIndexData[1] = 1; 
            waterIndexData[2] = 2;
            waterIndexData[3] = 3;
            waterIndexData[4] = 4;
            waterIndexData[5] = 5;

            _waterIndexBuffer = new IndexBuffer(_dDevice, typeof(short), 6, BufferUsage.WriteOnly);
            _waterIndexBuffer.SetData(waterIndexData);
        }
Пример #55
0
        public HexPoint CreatePoint(EPointPositionOnHex position, HexLocation location)
        {
            int w = location.W;
            int h = location.H;
            HexPoint result = new HexPoint();
            switch (position)
            {
                case EPointPositionOnHex.TopMiddle:
                    result.Hex1 = new HexLocation(w - 1, h - 1);
                    result.Hex2 = new HexLocation(w, h - 1);
                    result.Hex3 = new HexLocation(w, h);
                    break;
                case EPointPositionOnHex.RightTop:
                    result.Hex1 = new HexLocation(w, h - 1);
                    result.Hex2 = new HexLocation(w, h);
                    result.Hex3 = new HexLocation(w + 1, h);
                    break;
                case EPointPositionOnHex.RightBottom:
                    result.Hex1 = new HexLocation(w, h);
                    result.Hex2 = new HexLocation(w + 1, h);
                    result.Hex3 = new HexLocation(w, h + 1);
                    break;
                case EPointPositionOnHex.BottomMiddle:
                    result.Hex1 = new HexLocation(w, h);
                    result.Hex2 = new HexLocation(w - 1, h + 1);
                    result.Hex3 = new HexLocation(w, h + 1);
                    break;
            }

            return result;
        }
Пример #56
0
        private void UpdateInfluenceMaps()
        {
            //if (IsHuman)
            //    return;

            if (Map == null)
                return;

            if (CityLocationMap == null)
            {
                CityLocationMap = new InfluenceMap(Map.Width, Map.Height);
                ImprovementLocationMap = new InfluenceMap(Map.Width, Map.Height);
                FriendsInfluence = new InfluenceMap(Map.Width, Map.Height);
                EnemyInfluence = new InfluenceMap(Map.Width, Map.Height);
            }

            for (int x = 0; x < Map.Width; ++x)
            {
                for (int y = 0; y < Map.Height; ++y)
                {
                    HexPoint pt = new HexPoint(x, y);

                    #region city found map
                    MapCell cell = Map[x, y];
                    if (cell.IsSpotted(this))
                    {
                        float value = Map.GetValue(x, y, MapValueType.CityFoundValue);
                        CityLocationMap[x, y] = value;
                        ImprovementLocationMap[x, y] = value;

                        if (_cities.Count == 0)
                        {
                            int dist = HexPoint.GetDistance(pt, StartLocation);
                            if (dist < 2)
                                CityLocationMap[x, y] += 2;

                            if (dist < 1)
                                CityLocationMap[x, y] += 2;
                        }

                        if (GetCityAt(pt) != null)
                        {
                            CityLocationMap[pt] = 0;
                            ImprovementLocationMap[pt] = 0;
                        }

                        foreach (HexPoint n in pt.Neighbors)
                        {
                            if (GetCityAt(n) != null)
                            {
                                CityLocationMap[pt] = 0;
                                ImprovementLocationMap[x, y] *= 1.7f;
                            }
                        }
                    }
                    else
                        CityLocationMap[x, y] = 0;
                    #endregion city found map
                }
            }

            foreach(Unit unit in _units)
                FriendsInfluence.Apply(unit.Point, unit.Strength);

            //foreach(Unit enemyUnit in _unitsInSight)
            //{

            //}

            _needToUpdateInfluenceMaps = false;
        }
Пример #57
0
 void unit_Moved(Unit sender, HexPoint oldPosition, HexPoint newPosition)
 {
     _needToUpdateInfluenceMaps = true;
 }
Пример #58
0
        /// <summary>
        /// Calculates a path from start to end. When no path can be found in
        /// reasonable time the search is aborted and an incomplete path is returned.
        /// When refresh is not set to true a cached path is returned where possible.
        /// </summary>
        /// <param name="start">start position in 2d map space</param>
        /// <param name="end">end position in 2d map space</param>
        /// <param name="refresh">force to recalculate the path</param>
        /// <returns></returns>
        public Path CalculatePath(Unit unit, HexPoint start, HexPoint end, bool refresh = false)
        {
            // swap points to calculate the path backwards (from end to start)
            HexPoint temp = end;
            end = start;
            start = temp;

            // Check whether the requested path is already known
            PathRequest request = new PathRequest(unit,start, end);

            if (!refresh && knownPaths.ContainsKey(request))
            {
                return knownPaths[request].Copy();
            }

            // priority queue of nodes that yet have to be explored sorted in
            // ascending order by node costs (F)
            PriorityQueue<PathNode> open = new PriorityQueue<PathNode>();

            // list of nodes that have already been explored
            LinkedList<IGridCell> closed = new LinkedList<IGridCell>();

            // start is to be explored first
            PathNode startNode = new PathNode(unit,null, map[start], end);
            open.Enqueue(startNode);

            int steps = 0;
            PathNode current;

            do
            {
                // abort if calculation is too expensive
                if (++steps > stepLimit) return null;

                // examine the cheapest node among the yet to be explored
                current = open.Dequeue();

                // Finish?
                if (current.Cell.Matches(end))
                {
                    // paths which lead to the requested goal are cached for reuse
                    Path path = new Path(current);

                    if (knownPaths.ContainsKey(request))
                    {
                        knownPaths[request] = path.Copy();
                    }
                    else
                    {
                        knownPaths.Add(request, path.Copy());
                    }

                    return path;
                }

                // Explore all neighbours of the current cell
                ICollection<IGridCell> neighbours = map.GetNeighbourCells(current.Cell);

                foreach (IGridCell cell in neighbours)
                {
                    // discard nodes that are not of interest
                    if (closed.Contains(cell) || (cell.Matches(end) == false && !cell.IsWalkable(unit)))
                    {
                        continue;
                    }

                    // successor is one of current's neighbours
                    PathNode successor = new PathNode(unit,current, cell, end);
                    PathNode contained = open.Find(successor);

                    if (contained != null && successor.F >= contained.F)
                    {
                        // This cell is already in the open list represented by
                        // another node that is cheaper
                        continue;
                    }
                    else if (contained != null && successor.F < contained.F)
                    {
                        // This cell is already in the open list but on a more expensive
                        // path -> "integrate" the node into the current path
                        contained.Predecessor = current;
                        contained.Update();
                        open.Update(contained);
                    }
                    else
                    {
                        // The cell is not in the open list and therefore still has to
                        // be explored
                        open.Enqueue(successor);
                    }
                }

                // add current to the list of the already explored nodes
                closed.AddLast(current.Cell);

            } while (open.Peek() != null);

            return null;
        }
Пример #59
0
 public PathRequest(Unit unit, HexPoint start, HexPoint end)
 {
     data = unit.Data;
     this.start = start;
     this.end = end;
 }
Пример #60
0
 private bool IsAllSea(HexPoint point, XmlBoard board)
 {
     return false;
     /*
     if (board.Hexes[point.Hex1] is SeaHex &&
         board.Hexes[point.Hex2] is SeaHex &&
         board.Hexes[point.Hex3] is SeaHex)
         return true;
     else
         return false;
      */
 }