Exemplo n.º 1
0
    public MyGame(string[] tmxFileNames, int levelIndex) :
        base(SCREEN_WIDTH, SCREEN_HEIGHT, FULLSCREEN) // Create a window that's 800x600 and NOT fullscreen
    {
        GL.ClearColor(1f, 1f, 1f, 1f);

        ThisInstance = this;

        _levelFiles = tmxFileNames;

        if (_levelFiles.Length == 0)
        {
            throw new ApplicationException(
                      $"_levelFiles.Length == 0, no tmx files found in {AppDomain.CurrentDomain.DynamicDirectory}");
        }

        LoadScoreBoardData();

        _mapData = TiledMapParserExtended.MapParser.ReadMap(_levelFiles[levelIndex]);

        _map = new MapGameObject(_mapData);

        _camera = new FollowCamera(0, 0, width, height);

        _canvasDebugger = new CanvasDebugger2(width, height);

        AddChild(SoundManager.Instance);

        var hudScreenFader = new HudScreenFader();

        StartScreen();

        //var startScreen = new StartScreen();
        //AddChild(startScreen);
    }
        public void UpdateObjectTree()
        {
            MainWindow.mainWindow.ObjectTree.Children.Clear();

            foreach (GameObject obj in objectManager.GetObjects())
            {
                MapGameObject mapObject = obj as MapGameObject;

                if (mapObject != null)
                {
                    CheckBoxPair checkPair = new CheckBoxPair();
                    string       name      = "";

                    foreach (KeyValuePair <string, GameObjectProperty> property in mapObject.Properties)
                    {
                        if (property.Key == "Name")
                        {
                            name = property.Value.CurrentValue;
                        }
                    }

                    checkPair.MainLabel.Text = name;

                    checkPair.MainCheckBox.IsChecked = mapObject.Visible;

                    checkPair.MainCheckBox.Click += (sender, e) =>
                    {
                        mapObject.Visible = (bool)checkPair.MainCheckBox.IsChecked;
                    };

                    MainWindow.mainWindow.ObjectTree.Children.Add(checkPair);
                }
            }
        }
Exemplo n.º 3
0
        public MapJSON GetCurrentMap()
        {
            Color bgColor = MainWindowViewModel.viewModel.BackgroundColor;

            MapJSON map = new MapJSON()
            {
                BackgroundR = bgColor.R,
                BackgroundG = bgColor.G,
                BackgroundB = bgColor.B
            };

            foreach (GameObject obj in MainWindowViewModel.viewModel.objectManager.GetObjects())
            {
                MapGameObject mapObject = obj as MapGameObject;

                if (mapObject != null)
                {
                    map.Objects.Add(new MapObjectJSON()
                    {
                        Layer      = mapObject.Layer,
                        PositionX  = mapObject.GetPosition().X,
                        PositionY  = mapObject.GetPosition().Y,
                        Properties = mapObject.Properties,
                        Info       = mapObject.Info,
                        Name       = mapObject.Name,
                        Components = mapObject.Components
                    });
                }
            }

            return(map);
        }
Exemplo n.º 4
0
 public void ShowMap()
 {
     if (MapGameObject == null)
     {
         return;
     }
     MapGameObject.SetActive(true);
 }
Exemplo n.º 5
0
 public void HideMap()
 {
     if (MapGameObject == null)
     {
         return;
     }
     MapGameObject.SetActive(false);
 }
Exemplo n.º 6
0
    /// <summary>
    /// Method to reload the game object for this building.
    /// Used by game manager to reload buildings in the case that the owning faction has changed
    /// </summary>
    public void ReloadBuildingObject()
    {
        Vector3 uniOriginalPosVector3;

        uniOriginalPosVector3 = ObjectPosition;
        GameObject.Destroy(MapGameObject);
        MapGameObject = CreateBuildingObject(BuildingType, OwningFaction.Type);
        MapGameObject.transform.localScale = new Vector3(ObjectRadius, ObjectRadius, ObjectRadius);
        ObjectPosition = uniOriginalPosVector3;
        if (MapGameObject.GetComponent <LineRenderer>() == null)
        {
            MapGameObject.AddComponent <LineRenderer>();
        }
    }
Exemplo n.º 7
0
    /// <summary>
    /// Method for upgrading the current instance of building
    /// Performs checks for material count and current upgrade tier
    /// Virtual method to allow overriding for different upgrade cost calculations or functionality for future building classes.
    /// </summary>
    /// <param name="pblnOutline">specify false to not outline on upgrade. When enemies upgrade.</param>
    /// <param name="pblnNoCost">Specify true to ignore cost calculations</param>
    /// <returns></returns>
    public virtual bool UpgradeBuilding(bool pblnOutline = true, bool pblnNoCost = false)
    {
        bool    blnUpgraded     = false;
        int     intBuildingCost = 0;
        Vector3 uniOriginalPosVector3;
        string  strResourceKey;

        if (!pblnNoCost)
        {
            intBuildingCost = CalculateBuildingUpgradeCost(BuildingType, UpgradeLevel + 1);
        }
        // Check if upgrade is allowed
        if (OwningFaction.MaterialCount > intBuildingCost &&
            UpgradeLevel < 3 && // Can't upgrade past 3
            OwningFaction.GodTier >= UpgradeLevel)
        {
            blnUpgraded = true;
            OwningFaction.MaterialCount -= intBuildingCost;
            UpgradeLevel++;

            // Load the new model, swap the models, and move the building back into place.
            // Allows for completely different models on upgrade
            strResourceKey = "Buildings/" + OwningFaction.Type.ToString() + BuildingType.ToString() + UpgradeLevel.ToString();
            if (mdictBuildingResources.ContainsKey(strResourceKey) && mdictBuildingResources[strResourceKey] != null)
            {
                uniOriginalPosVector3 = ObjectPosition;
                GameObject.Destroy(MapGameObject);
                MapGameObject = (GameObject)GameObject.Instantiate(
                    mdictBuildingResources[strResourceKey]);
                MapGameObject.transform.localScale = new Vector3(ObjectRadius, ObjectRadius, ObjectRadius);
                ObjectPosition = uniOriginalPosVector3;
                MapGameObject.AddComponent <LineRenderer>();
                if (pblnOutline)
                {
                    ToggleObjectOutlines(true);
                }
            }
            else
            {
                MapGameObject.transform.localScale += new Vector3(1, 1, 1); // In case no model exists yet
            }
        }
        // Return whether the upgrade was successfull to allow feedback to the player
        return(blnUpgraded);
    }
Exemplo n.º 8
0
        /// <summary>
        /// Gets the prediction.
        /// </summary>
        /// <param name="fromPos">Position where projectile gets fired from.</param>
        /// <param name="targetUnit">The target unit.</param>
        /// <param name="range">The ability range.</param>
        /// <param name="speed">The ability speed.</param>
        /// <param name="radius">The ability radius (for collision).</param>
        /// <param name="fixedDelay">The fixed delay. If greater than 0, will use this fixed delay for calculations instead of getting normal best position prediction</param>
        /// <param name="maxEnemyReactionTime">The maximum enemy reaction time in seconds to calculate HitChance.</param>
        /// <param name="checkCollision">If set to <c>true</c> [check collision].</param>
        /// <param name="ignoreFlags">The ignore flags for collision calculations.</param>
        /// <returns>TestOutput</returns>
        public static TestOutput GetPrediction(Vector2 fromPos, InGameObject targetUnit, float range, float speed,
                                               float radius               = 0f,
                                               float fixedDelay           = 0f,
                                               float maxEnemyReactionTime = 1.75f,
                                               bool checkCollision        = false,
                                               CollisionFlags ignoreFlags = CollisionFlags.Bush | CollisionFlags.NPCBlocker)
        {
            MapGameObject         mapGameObject         = targetUnit.Get <MapGameObject>();
            NetworkMovementObject networkMovementObject = targetUnit.Get <NetworkMovementObject>();

            if (mapGameObject == null)
            {
                Logs.Error("TestPrediction: Object of name " + targetUnit.ObjectName + " has no MapGameObject model");
                return(new TestOutput()
                {
                    CanHit = false,
                    Hitchance = TestHitchance.Impossible,
                    CastPosition = Vector2.Zero,
                });
            }

            var targetPos = mapGameObject.Position;

            if (networkMovementObject == null)
            {
                Logs.Error("TestPrediction: Object of name " + targetUnit.ObjectName + " has no NetworkMovementObject model");
                return(new TestOutput()
                {
                    CanHit = targetPos.Distance(fromPos) <= range ? true : false,
                    Hitchance = targetPos.Distance(fromPos) <= range ? TestHitchance.VeryHigh : TestHitchance.OutOfRange,
                    HitchancePercentage = targetPos.Distance(fromPos) <= range ? 100f : 0f,
                    CastPosition = targetPos,
                });
            }

            var targetVelocity = networkMovementObject.Velocity;
            var targetRadius   = targetUnit.Get <SpellCollisionObject>().SpellCollisionRadius; //TODO: Check if MapCollisionRadius is better

            if (fixedDelay < float.Epsilon)                                                    //No fixed delay
            {
                var predPos = GetStandardPrediction(fromPos, targetPos, speed, targetVelocity);
                if (predPos == Vector2.Zero)
                {
                    return(new TestOutput()
                    {
                        CanHit = false,
                        Hitchance = TestHitchance.Impossible,
                        CastPosition = Vector2.Zero,
                    });
                }


                TestOutput solution = new TestOutput()
                {
                    CanHit       = true,
                    CastPosition = predPos,
                };

                var targetCollision = CollisionSolver.CheckThickLineCollision(targetPos, solution.CastPosition, targetRadius);
                if (targetCollision != null && targetCollision.IsColliding)
                {
                    solution.CastPosition = targetCollision.CollisionPoint;
                }

                if (solution.CastPosition.Distance(fromPos) > range)
                {
                    solution.CanHit    = false;
                    solution.Hitchance = TestHitchance.OutOfRange;
                }

                if (checkCollision)
                {
                    solution.CollisionResult = CollisionSolver.CheckThickLineCollision(fromPos, solution.CastPosition, radius < float.Epsilon ? 0.01f : radius, ignoreFlags);

                    if (solution.CollisionResult.IsColliding)
                    {
                        solution.CanHit    = false;
                        solution.Hitchance = TestHitchance.Collision;
                    }
                }

                solution.HitchancePercentage = GetHitchance(fromPos, solution.CastPosition, speed, maxEnemyReactionTime, false);
                solution.Hitchance           = GetHitchanceEnum(solution.HitchancePercentage);
                return(solution);
            }
            else //WITH fixed delay
            {
                var predPos = GetFixedDelayPrediction(targetPos, fixedDelay, targetVelocity);

                TestOutput solution = new TestOutput()
                {
                    CanHit       = true,
                    CastPosition = predPos,
                };

                var targetCollision = CollisionSolver.CheckThickLineCollision(targetPos, solution.CastPosition, targetRadius);
                if (targetCollision != null && targetCollision.IsColliding)
                {
                    solution.CastPosition = targetCollision.CollisionPoint;
                }

                if (solution.CastPosition.Distance(fromPos) > range)
                {
                    solution.CanHit    = false;
                    solution.Hitchance = TestHitchance.OutOfRange;
                }

                solution.HitchancePercentage = GetHitchance(fromPos, solution.CastPosition, fixedDelay, maxEnemyReactionTime, true);
                solution.Hitchance           = GetHitchanceEnum(solution.HitchancePercentage);
                return(solution);
            }
        }
Exemplo n.º 9
0
 public TrackedObstacleObject(MapGameObject mapObject, ObstacleAbilityInfo data)
 {
     MapObject = mapObject;
     Data      = data;
 }
Exemplo n.º 10
0
 public static bool IsHoveringNear(this MapGameObject obj)
 {
     return(new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y + 1).ScreenToWorld().Distance(obj.Position) < 1);
 }
        public void WPFMouseDown(MouseEventArgs e)
        {
            ComboBox comboBox = MainWindow.mainWindow.ObjectComboBox;

            ComboBoxObjectInfoItem item = comboBox.SelectedItem as ComboBoxObjectInfoItem;
            Vector2 worldPos            = Vector2.Transform(new Vector2((float)e.GetPosition(MainWindow.mainWindow.Viewport).X, (float)e.GetPosition(MainWindow.mainWindow.Viewport).Y), Matrix.Invert(objectManager.CurrentCamera.Transform));

            // Placing objects
            if (e.LeftButton == MouseButtonState.Pressed && SelectionType == SelectionType.OBJECT && item != null && !guiManager.UIHovered)
            {
                MapGameObject mapObject = new MapGameObject(item.GameObject.Copy());

                if (item.GameObject == null)
                {
                    Console.WriteLine("GameObjectInfo is null!");
                }

                mapObject.SetPosition(objectManager.PreviewObject.GetPosition());

                mapObject.CurrentAnimation = objectManager.PreviewObject.CurrentAnimation;
                mapObject.Properties       = item.GameObject.Properties;
                mapObject.Info             = item.GameObject.Copy();
                mapObject.HelperRectangles = item.GameObject.HelperRectangles;

                objectManager.GetObjects().Add(mapObject);

                UpdateObjectTree();
            }

            // Selecting objects
            if (e.LeftButton == MouseButtonState.Pressed && SelectionType == SelectionType.SELECTION && !guiManager.UIHovered)
            {
                // Ensure the mouse is not already over a selected object.
                bool isSelectionHovered = false;

                foreach (GameObject obj in objectManager.SelectionObject.Selection)
                {
                    if (obj.GetBoundingBox().Intersects(new Rectangle((int)worldPos.X, (int)worldPos.Y, 1, 1)))
                    {
                        isSelectionHovered = true;
                    }
                }

                if (!isSelectionHovered || (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
                {
                    if (!Keyboard.IsKeyDown(Key.LeftShift) && !Keyboard.IsKeyDown(Key.RightShift))
                    {
                        objectManager.SelectionObject.Selection = new List <GameObject>();
                    }


                    foreach (GameObject obj in objectManager.GetObjects())
                    {
                        if (new Rectangle((int)worldPos.X, (int)worldPos.Y, 1, 1).Intersects(obj.GetBoundingBox()) && !objectManager.SelectionObject.Selection.Contains(obj) && obj != objectManager.PreviewObject && obj.Visible)
                        {
                            if (!Keyboard.IsKeyDown(Key.LeftShift) && !Keyboard.IsKeyDown(Key.RightShift))
                            {
                                if (objectManager.SelectionObject.Selection.Count == 0)
                                {
                                    objectManager.SelectionObject.Selection.Add(obj);
                                }

                                else
                                {
                                    objectManager.SelectionObject.Selection[0] = obj;
                                }
                            }
                            else
                            {
                                objectManager.SelectionObject.Selection.Add(obj);
                            }

                            GameObjectAnimated animObj = objectManager.SelectionObject.Selection[0] as GameObjectAnimated;

                            if (animObj != null && animObj.CurrentAnimation != null)
                            {
                                animObj.CurrentAnimation.SetCurrentMS(0);
                                animObj.CurrentAnimation.Play();
                            }
                            if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                            {
                                break;
                            }
                        }
                    }
                }
            }

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                UpdateLayerBox();
            }

            if (e.LeftButton == MouseButtonState.Pressed && objectManager.SelectionObject.Selection.Count > 0)
            {
                OldPositions = new List <Vector2>();

                foreach (GameObject obj in objectManager.SelectionObject.Selection)
                {
                    OldPositions.Add(obj.GetPosition());
                }

                isMoving = true;
            }

            /// OBJECT MOVING

            // Get relative position to origin of selection
            if (objectManager.SelectionObject.Selection != null)
            {
                foreach (GameObject gameObject in objectManager.SelectionObject.Selection)
                {
                    if (gameObject is MapGameObject)
                    {
                        grabOffset[gameObject] = worldPos - gameObject.GetPosition();
                    }
                }
            }
        }
Exemplo n.º 12
0
        public void Draw(GameTime gameTime, GraphicsDevice device, SpriteBatch spriteBatch, GameInfo info)
        {
            if (info == null)
            {
                return;
            }

            Screen currentScreen = GetScreen(CurrentScreen);

            if (_RenderTarget != null && UseVirtualSize)
            {
                info.graphicsDevice.SetRenderTarget(_RenderTarget);
            }

            // Only do this on the GUI layer so that it doesn't overwrite the object layer.
            if (_RenderTarget != null)
            {
                info.graphicsDevice.Clear(Color.Transparent);
            }

            StartDefaultSpriteBatch(spriteBatch);

            if (currentScreen != null)
            {
                currentScreen.Draw(gameTime, device, spriteBatch, info);
            }

            // Draw name above currently selected objects
            if (info.objectManager.SelectionObject != null && info.objectManager.SelectionObject.Selection != null)
            {
                foreach (GameObject gameObject in info.objectManager.SelectionObject.Selection)
                {
                    if (gameObject.Properties.ContainsKey("Name"))
                    {
                        MapGameObject mapObject = gameObject as MapGameObject;

                        float textScale            = 0.5f;
                        float transformedTextScale = textScale / (float)info.objectManager.CurrentCamera.LerpZoom;

                        if (mapObject != null)
                        {
                            string shownText = $"{mapObject.Properties["Name"].CurrentValue} ({mapObject.Info.DisplayName})";

                            Size2 stringHeight = ContentLoader.GetFont("engine_font").MeasureString(shownText);

                            spriteBatch.DrawString(ContentLoader.GetFont("engine_font"), shownText, Vector2.Transform(new Vector2((int)mapObject.GetPosition().X, (int)mapObject.GetPosition().Y - (stringHeight.Height * transformedTextScale) - 2), (Matrix)info.objectManager.CurrentMatrix), Color.White, 0.0f, new Vector2(0, 0), textScale, SpriteEffects.None, 0f);
                        }
                    }
                }
            }



            SwitchToDefaultSpriteBatch(spriteBatch);

            if (UseVirtualSize)
            {
                info.graphicsDevice.SetRenderTarget(null);
            }

            // Draw render target to screen so we can "stretch" the viewport if needed.
            Rectangle bounds = new Rectangle(0, 0, info.graphicsDevice.PresentationParameters.BackBufferWidth, info.graphicsDevice.PresentationParameters.BackBufferHeight);

            if (UseVirtualSize)
            {
                spriteBatch.Draw(_RenderTarget, bounds, Color.White);
            }

            spriteBatch.End();
        }
Exemplo n.º 13
0
        public void OpenProject()
        {
            OpenFileDialog projectDialog = new OpenFileDialog();

            projectDialog.Filter = "Pest Control Map Project (*.mapproj)|*.mapproj";

            if (projectDialog.ShowDialog() == true)
            {
                projectManager.ProjectPath = projectDialog.FileName;

                // Clear objects of map objects
                List <MapGameObject> toRemove = new List <MapGameObject>();

                foreach (GameObject obj in MainWindowViewModel.viewModel.objectManager.GetObjects())
                {
                    MapGameObject mapObject = obj as MapGameObject;

                    if (mapObject != null)
                    {
                        toRemove.Add(mapObject);
                    }
                }

                foreach (MapGameObject obj in toRemove)
                {
                    MainWindowViewModel.viewModel.objectManager.GetObjects().Remove(obj);
                }

                // Add new map objects from json file
                string jsonInput = File.ReadAllText(projectDialog.FileName);

                MapJSON map = JsonConvert.DeserializeObject <MapJSON>(jsonInput);

                MainWindowViewModel.viewModel.BackgroundColor = new Color(map.BackgroundR, map.BackgroundG, map.BackgroundB);

                foreach (MapObjectJSON objectJson in map.Objects)
                {
                    MapGameObject mapObject = new MapGameObject(objectJson.Info)
                    {
                        Properties       = objectJson.Properties,
                        Layer            = objectJson.Layer,
                        Name             = objectJson.Name,
                        HelperRectangles = objectJson.Info.HelperRectangles,
                        Components       = objectJson.Components
                    };

                    mapObject.SetPosition(new Vector2(objectJson.PositionX, objectJson.PositionY));

                    mapObject.CurrentAnimation = objectJson.Info.DefaultAnimation;

                    MainWindowViewModel.viewModel.objectManager.GetObjects().Add(mapObject);
                }
            }
            else
            {
                return;
            }

            // Update background color box
            Color backColor = MainWindowViewModel.viewModel.BackgroundColor;

            BackColorTextBox.Text = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(255, backColor.R, backColor.G, backColor.B));

            UpdateTitleBar();
        }