root/src/AIDemos/Screens/Demos/Demo6.cs

User picture

Author: conkerjo

Revision: 30 («Previous)


File Size: 7.79 KB

(July 12, 2009 15:10 UTC) Almost 3 years ago


  

 
Show/hide line numbers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using AIDemos;
using Microsoft.Xna.Framework.Content;
using System.Threading;
using Microsoft.Xna.Framework.Input;
using Brains.Framework;
using AIRendering;
using AIDemos.GameClasses;
using Brains;
using Brains.Framework.Behaviors;
using AIDemos.GameClasses.Behaviors;
using System.Collections;
using Brains.Framework.Map;
using Brains.Framework.Utility;
using AIDemos.GameClasses.Behaviors.Conditions;
using AIDemos.GameClasses.Behaviors.Decorators;

namespace AIDemos.Screens.Demos
{
    public class Demo6 : DemoGameScreen
    {

        GridCell _endNode;
        public Demo6():base("Demo 6 - Combining Behaviors","The main actor will patrol until an enemy is seen\nIt will then attack the enemy until it is dead")
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
                
        }

        public override void LoadContent()
        {
            base.LoadContent();
            
            LoadAI();

            CenterCamOnMap();
            ScreenManager.Game.ResetElapsedTime();
        }
        Soldier _secretAgent;
        private void LoadAI()
        {
            _engine.CreateWorld(new DrawableWorld());
            _engine.World.LoadMapDataFromTexture(
                content.Load<Texture2D>("DemoTextures/MAPDemo2"),
                32,
                typeof(DrawableGrid));

            GridCell fromcell=_engine.World.Map.AllCells.First<GridCell>(
                a => a.Labels[AIConsts.COLORR]==0&&
                    a.Labels[AIConsts.COLORG]==255 &&
                    a.Labels[AIConsts.COLORB]==0);
         
            _secretAgent= new Soldier(fromcell.Position, 10);
            _secretAgent.Locomotion = new Brains.Framework.Locomotion.LocomtionSteering();
            _secretAgent.Locomotion.MaxSpeed = 50;
            _secretAgent.Locomotion.MaxRotation = MathHelper.TwoPi;

            _engine.World.AddActor(_secretAgent);
            RootSoldierBehavior root = new RootSoldierBehavior();
            //***Idle***
            ParallelBehavior _idle = new ParallelBehavior();
            //If there are no enemies nearby
            EnemyNearby _enemy = new EnemyNearby();
            _enemy.ConditionCheck = false;
            _idle.SubBehaviors.Add(_enemy);

            //Patrol for 10 seconds
            IEnumerable<GridCell> cells = _engine.World.Map.AllCells.Where(
                                                    a => a.Labels[AIConsts.COLORG] == 255 &&
                                                    a.Labels[AIConsts.COLORR] < 10 && //Hack - Limit number of patrol points to 10
                                                    a.Labels[AIConsts.COLORB] == 0
                                                    );
            GridCell[] _arrayofCells = cells.ToArray<GridCell>();
            Array.Sort(_arrayofCells, new CellComparer());
            DrawableCyclicRoute _route = new DrawableCyclicRoute();
            foreach (var item in _arrayofCells)
            {
                _route.AddPoint(item);
            }
            

            TimerBehavior _time = new TimerBehavior();
            _time.Time = 10;
            _time.SubBehaviors.Add(_route);
            
            _idle.SubBehaviors.Add(_time);

            root.SubBehaviors.Add(_idle);

            //Attack
            SequenceBehavior _attack = new SequenceBehavior();
            //If there are no enemies nearby
            EnemyNearby _enemy1 = new EnemyNearby();
            _enemy1.ConditionCheck = true;
            _attack.SubBehaviors.Add(_enemy1);

            AttackBehavior _atk = new AttackBehavior();
            _attack.SubBehaviors.Add(_atk);
            root.SubBehaviors.Add(_attack);
            _secretAgent.RootBehavior = root;

        }
        class CellComparer:IComparer
        {
            
            public int Compare(object x, object y)
            {
                GridCell p1;
                GridCell p2;

                if (x is GridCell)
                    p1 = x as GridCell;
                else
                    throw new ArgumentException("Object is not of type GridCell.");

                if (y is GridCell)
                    p2 = y as GridCell;
                else
                    throw new ArgumentException("Object is not of type GridCell.");

                return p1.Labels[AIConsts.COLORR].CompareTo(p2.Labels[AIConsts.COLORR]);
            }
        }
        
        public override void UnloadContent()
        {
            content.Unload();
        }

        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                     bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            if (IsActive)
            {
                _engine.Update(gameTime);


                Vector2 mousPos = new Vector2(_currentMouse.X, _currentMouse.Y);

                if (_currentMouse.LeftButton == ButtonState.Released &&
                    _lastMouse.LeftButton == ButtonState.Pressed)
                {
                    Vector2 mapMousePos = mousPos + primitiveBatch.CameraPosition;
                    GridCell cell = _engine.World.Map.ClusterGrid.Grids[0].GetCellAtPosition(mapMousePos);
                    if (cell != null)
                    {
                        GameActor actor = new GameActor(cell.Position, 5);
                        actor.Locomotion = new Brains.Framework.Locomotion.LocomotionController();
                        actor.Locomotion.MaxSpeed = 30;
                        actor.Locomotion.MaxRotation = MathHelper.TwoPi;

                        _engine.World.AddActor(actor);
                        SequenceBehavior _sequence = new SequenceBehavior();

                        DrawableBehaviorGoTo _goto = new DrawableBehaviorGoTo();
                        _goto.StartNode = cell;
                        _goto.EndNode = _secretAgent.CellsIAmIn[0];
                        _sequence.SubBehaviors.Add(_goto);
                        _sequence.SubBehaviors.Add(new DieBehavior());
                        actor.RootBehavior = _sequence;
                    }
                }
            }
        }
        MouseState _currentMouse;
        MouseState _lastMouse;
        public override void HandleInput(InputState input)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            _lastMouse = _currentMouse;
            _currentMouse = Mouse.GetState();


            int playerIndex = (int)ControllingPlayer.Value;
            
            KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
            GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];

            bool gamePadDisconnected = !gamePadState.IsConnected &&
                                       input.GamePadWasConnected[playerIndex];

           

            base.HandleInput(input);
        }

        public override void Draw(GameTime gameTime)
        {
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.Black, 0, 0);

            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            spriteBatch.Begin();
            
            base.Draw(gameTime);
            ((IRender)_engine.World).Render(primitiveBatch);
            spriteBatch.End();

            
            if (TransitionPosition > 0)
                ScreenManager.FadeBackBufferToBlack(255 - TransitionAlpha);
        }
    }
}