Пример #1
0
        private Bumpership CreateBumpership(PlayerType player, IInputHandler keyboardHandler, SocketManager socketManager, ref int countShip)
        {
            IInputHandler input;
            string        name = "";

            switch (player)
            {
            case PlayerType.Human:
                input = keyboardHandler;
                name  = "Human";
                break;

            case PlayerType.AI:
                input = socketManager.GetNetworkPlayer();
                break;

            default:
                input = new IdiotAi();     // Test
                break;
            }
            Vector startPosition = world.Map.StartPositions[countShip];

            countShip++;
            return(new Bumpership(input, world, graphics.CreateShip(), name, startPosition));
        }
Пример #2
0
    void Start()
    {
        var ship = new Redball(new BallSpec(10, 2));

        _Movement     = new Movement();
        _inputHandler = (IInputHandler) new BallInput();
    }
Пример #3
0
        public GameManager(
            GameSettings gameSettings,
            IInputHandler keyboardHandler,
            SocketManager socketManager,
            IGraphicsHandler graphics)
        {
            this.gameSettings = gameSettings;
            this.graphics     = graphics;
            const int ticksPerSecond = 30;

            gameLoop         = new GameLoop(5, ticksPerSecond);
            gameLoop.Update += Update;
            gameLoop.Render += Render;

            Map map = new Map(gameSettings.Map);

            world = new World(map);

            int countShip = 0;
            List <Bumpership> bumperships = gameSettings.Players.Take(world.Map.StartPositions.Count)
                                            .Select(p => CreateBumpership(p, keyboardHandler, socketManager, ref countShip))
                                            .ToList();

            world.AddShips(bumperships);
        }
Пример #4
0
 public BookStoreEngine(IRenderer renderer, IInputHandler inputHandler)
 {
     this.renderer = renderer;
     this.inputHandler = inputHandler;
     this.books = new List<IBook>();
     this.revenue = 0;
 }
Пример #5
0
        static void ProcessInputAction(IInputHandler handler, InputEvent action, double value, WindowState state)
        {
            var items = SelectionManager.SelectedItems();

            switch (action)
            {
            case InputEvent.None:
                return;

            case InputEvent.DragEnter:
                handler.OnEnterDrag(items, state);
                break;

            case InputEvent.Drag:
                handler.OnDrag(value, state);
                break;

            case InputEvent.DragExit:
                handler.OnExitDrag();
                break;

            case InputEvent.KeyboardInput:
                handler.OnSetValue(items, value, state);
                break;

            default:
                return;
            }
        }
Пример #6
0
        /// <summary>
        /// Initialize the Service
        /// </summary>
        /// <param name="context">The executable context</param>
        public override void Init(IExecutableContext context)
        {
            KeyTopicDictionary = new Dictionary <Key, string>();
            handler            = new InputHandler();

            base.Init(context);
        }
Пример #7
0
 public Camera(Game game)
     : base(game)
 {
     graphics = (GraphicsDeviceManager)game.Services.GetService(typeof(IGraphicsDeviceManager));
     //Reference to the input handeler
     input = (IInputHandler)game.Services.GetService(typeof(IInputHandler));
 }
Пример #8
0
 public Crane(Game game, Camera camera)
     : base(game)
 {
     // TODO: Construct any child components here
     input = (IInputHandler)Game.Services.GetService(typeof(IInputHandler));
     this.camera = camera;
 }
Пример #9
0
    void Start()
    {
        inventory = new Dictionary <int, int>
        {
            { 0, 0 }
        };

        cash = PlayerPrefs.GetFloat("cash", 10f);
        AdjustCashText();
        miningSpeedLevel = PlayerPrefs.GetInt("miningSpeedLevel", 0);
        miningSpeed      = baseMiningSpeed + UpgradeStation.miningSpeedLevelModifiers[miningSpeedLevel];

        storageLevel   = PlayerPrefs.GetInt("storageLevel", 0);
        maxStorage     = baseStorage + UpgradeStation.storageLevelModifiers[storageLevel];
        currentStorage = 0;
        AdjustStorageBar();
        //CalculateInventorySize();

        fuelTankLevel = PlayerPrefs.GetInt("fuelTankLevel", 0);
        maxFuel       = baseFuel + UpgradeStation.fuelTankLevelModifiers[PlayerPrefs.GetInt("fuelTankLevel", 0)];
        currentFuel   = maxFuel;

        playerCanInteract   = true;
        playerCanMove       = true;
        playerCanMine       = true;
        listOfInteractables = new List <GameObject>();
        rb              = GetComponent <Rigidbody2D>();
        inputHandler    = GetComponent <IInputHandler>();
        raycastDistance = gameObject.GetComponent <BoxCollider2D>().bounds.size.x / 2f + 1.4f;
        fuelCanDrain    = true;
    }
Пример #10
0
        public void AddPrev <T>() where T : IInputHandler
        {
            var handler = CreateHandler <T>();

            handler.successor = _handler;
            _handler          = handler;
        }
Пример #11
0
        public bool ControlKeyPress(KeyInfo key)
        {
            bool handled = false;

            // send to this control
            IInputHandler handler = this as IInputHandler;

            if (handler != null)
            {
                if (key.Down)
                {
                    handled = handler.KeyDown(key);
                }
                else
                {
                    handled = handler.KeyUp(key);
                }
            }

            // send to child controls
            if (!handled)
            {
                foreach (Control control in mControls)
                {
                    handled = control.ControlKeyPress(key);
                }
            }

            return(handled);
        }
        public override void Initialize()
        {
            //Grab a reference to the IInputHandler service.
            InputHandler = GameServiceManager.GetService <IInputHandler>();

            base.Initialize();
        }
Пример #13
0
 public static void RegisterHandler(IInputHandler h)
 {
     lock (_Mutex)
     {
         _Hanlders.Add(h);
     }
 }
Пример #14
0
 public TetrisGameManager(ITetrisGame tetrisGame, IInputHandler consoleInputHandler, TetrisConsoleWriter tetrisConsoleWriter, ScoreManager scoreManager)
 {
     this.tetrisGame          = tetrisGame;
     this.consoleInputHandler = consoleInputHandler;
     this.tetrisConsoleWriter = tetrisConsoleWriter;
     this.scoreManager        = scoreManager;
 }
Пример #15
0
        private void HandleInput(IInputHandler handler, InputType input)
        {
            switch (input)
            {
            case InputType.Menu:
                this.ToggleOverlay();
                break;

            case InputType.Back:
                if (this.activeMenuContainer != this.primaryMenuContainer)
                {
                    this.CloseSecondContainer();
                }
                else
                {
                    this.ToggleOverlay();
                }

                break;

            case InputType.PreviousItem:
                this.activeMenuContainer.PreviousItem();
                break;

            case InputType.NextItem:
                this.activeMenuContainer.NextItem();
                break;

            case InputType.SelectItem:
                this.activeMenuContainer.GetSelectedItem().PerformAction();
                break;
            }
        }
Пример #16
0
 public void Begin(IInputHandler handler)
 {
     if (handler != null)
     {
         InputHandlers.Push(handler);
     }
 }
Пример #17
0
        /// <summary>
        /// Saves received handler to the XML into _Data/Xml/InputSettings.
        /// </summary>
        /// <param name="handler">Handler to be saved</param>
        public static void WriteHandler(IInputHandler handler)
        {
            if (Application.isEditor)
            {
                return;
            }

            const string folder = @"Xml\InputSettings";

            var path = Path.Combine(Application.dataPath, folder);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var filePath = Path.Combine(path, handler.Name) + ".xml";

            using (var sw = new StreamWriter(filePath))
            {
                var serializer = new XmlSerializer(typeof(SavingHandler));

                var sh = new SavingHandler(handler.JustPressed,
                                           handler.Pressed,
                                           handler.JustReleased,
                                           handler.Axes);

                serializer.Serialize(sw, sh);

                sw.Close();
            }
        }
Пример #18
0
 public void Begin(IInputHandler handler)
 {
     if (handler != null)
     {
         InputHandlers.Push(handler);
     }
 }
Пример #19
0
    public static void Remove(IInputHandler parent, IInputHandler child)
    {
        KInputHandler inputHandler  = GetInputHandler(parent);
        KInputHandler inputHandler2 = GetInputHandler(child);

        inputHandler.RemoveInputHandler(inputHandler2);
    }
 public static void RegisterHandler(IInputHandler handler)
 {
     if (!handlers.Contains(handler))
     {
         handlers.Add(handler);
     }
 }
Пример #21
0
        public void CreateDbUser(IInputHandler inputHandler)
        {
            IDbHandler         dbHandler = new DbHandler();
            IValidator <IUser> validator = new UserValidator();

            dbHandler.Login(inputHandler);
            Console.Clear();

            while (true)
            {
                var user = CreateUser(inputHandler);

                if (validator.Validate(user))
                {
                    try {
                        var _ = dbHandler.AddUserAsync(user).Result;
                        Console.WriteLine("User successfully added");
                        Console.WriteLine();
                    }
                    catch (AggregateException) {
                        Console.WriteLine();
                        Console.WriteLine("Unable to connect to database");
                    }
                }
                else
                {
                    Console.WriteLine("User input invalid");
                }

                if (inputHandler.PromptConfirm("Do you wish to add more users?") is false)
                {
                    break;
                }
            }
        }
Пример #22
0
    public static void Add(IInputHandler parent, IInputHandler child, int priority = 0)
    {
        KInputHandler inputHandler  = GetInputHandler(parent);
        KInputHandler inputHandler2 = GetInputHandler(child);

        inputHandler.AddInputHandler(inputHandler2, priority);
    }
Пример #23
0
 void Awake()
 {
     if (inputHandler != null && inputHandler is IInputHandler)
     {
         _inputHandler = (IInputHandler)inputHandler;
     }
 }
Пример #24
0
 public WeatherServiceApplication(IWeatherForecastProvider forecastProvider, IInputHandler inputHandler, IOutputHandler outputHandler, IConfigDisplayGenerator configDisplayGenerator)
 {
     _forecastProvider       = forecastProvider;
     _inputHandler           = inputHandler;
     _outputHandler          = outputHandler;
     _configDisplayGenerator = configDisplayGenerator;
 }
Пример #25
0
        private void ReplaceText(IInputHandler argsHandler)
        {
            if (argsHandler.ArgumentsLeft < 2)
            {
                _out.WriteLine($"Not Enougth arguments {argsHandler.ArgumentsLeft}");
                return;
            }

            try
            {
                var position  = GetItemPositionFormStr(argsHandler.GetNextStringArg());
                var item      = _document.GetItem(position);
                var paragraph = item.Paragraph;
                if (paragraph != null)
                {
                    var text = CreateTextFromArr(argsHandler);
                    paragraph.SetParagraphText(text);
                }
                else
                {
                    throw new ArgumentException("paragraph not found");
                }
            }
            catch (Exception ex)
            {
                _out.WriteLine(ex.Message);
            }
        }
Пример #26
0
        private void ResizeImage(IInputHandler argsHandler)
        {
            if (argsHandler.ArgumentsLeft != 3)
            {
                _out.WriteLine($"Not Enougth arguments {argsHandler.ArgumentsLeft}");
                return;
            }

            try
            {
                var position = GetItemPositionFormStr(argsHandler.GetNextStringArg());
                var width    = argsHandler.GetNextIntArg();
                var height   = argsHandler.GetNextIntArg();
                var item     = _document.GetItem(position);
                var image    = item.Image;
                if (image != null)
                {
                    image.Resize(width, height);
                }
                else
                {
                    throw new ArgumentException("image not found");
                }
            }
            catch (Exception ex)
            {
                _out.WriteLine(ex.Message);
            }
        }
Пример #27
0
        private void ShowDocumentAsList(IInputHandler argsHandler)
        {
            try
            {
                _out.WriteLine($"Title: {_document.GetTitle()}");
                for (var i = 0; i < _document.GetItemsCount(); ++i)
                {
                    var          info      = $"{i}. ";
                    DocumentItem item      = _document.GetItem(i);
                    IImage       image     = item.Image;
                    IParagraph   paragraph = item.Paragraph;

                    if (image != null)
                    {
                        info += $"Image: { image.Width } { image.Height }  { image.Path }";
                    }
                    else if (paragraph != null)
                    {
                        info += $"Paragraph: { paragraph.GetParagraphText() }";
                    }

                    _out.WriteLine(info);
                }

                _out.WriteLine();
            }
            catch (Exception ex)
            {
                _out.WriteLine(ex.Message);
            }
        }
Пример #28
0
 protected void SetEvent(string mapName, string actionName, IInputHandler handler, InputEventHandleAction handleAction)
 {
     if (actionMaps.ContainsKey(mapName) && actionMaps[mapName].ContainsAction(actionName))
     {
         SetEvent(actionMaps[mapName].GetAction(actionName), InputEventType.KeyUp, handleAction, handler);
     }
 }
 public GameController(IGameEngine gameEngine, IInputHandler inputReader, IRenderer renderer)
 {
     this.gameEngine = gameEngine;
     this.inputReader = inputReader;
     this.renderer = renderer;
     this.currentCmd = null;
 }
Пример #30
0
 public Camera(Game game)
     : base(game)
 {
     graphics = (GraphicsDeviceManager)game.Services.GetService(typeof(IGraphicsDeviceManager));
     //Henter ut en referanse til input-handleren:
     input = (IInputHandler)game.Services.GetService(typeof(IInputHandler));
 }
Пример #31
0
 public GameEngine(IRenderer renderer, IInputHandler inputHandler, IPlayer player)
 {
     this.entities = MapInitializer.PopulateMap();
     this.renderer = renderer;
     this.inputHandler = inputHandler;
     this.player = player;
 }
Пример #32
0
        /// <summary>
        ///
        /// </summary>
        public Stage(Game game, IInputHandler handler)
        {
            _inst      = this;
            _wic       = handler;
            Stage.game = game;

            if (handler == null)
            {
                game.Window.TextInput += WindowOnTextInput;
            }

            soundVolume = 1;

            _batch        = new FairyBatch();
            _soundEnabled = true;

            _touchInfo         = new TouchInfo();
            _touchInfo.touchId = 0;
            _lastKeyDownTime   = new Dictionary <Keys, float>();

            _rollOutChain  = new List <DisplayObject>();
            _rollOverChain = new List <DisplayObject>();

            _focusRemovedDelegate = OnFocusRemoved;
        }
Пример #33
0
        /// <summary>
        /// Initialises a new instance of the <see cref="SimulationScreen"/> class.
        /// </summary>
        /// <param name="renderWindow">The render window to which to display this instance.</param>
        /// <param name="inputHandler">The input handler for this instance.</param>
        /// <param name="bodies">The bodies managed by this instance.</param>
        /// <param name="bodyShapeMap">The shapes for the bodies managed by this instance.</param>
        /// <param name="bodyPositionUpdater">The body position update delegate for this instance.</param>
        public SimulationScreen(RenderWindow renderWindow, IInputHandler inputHandler, ref Body[] bodies,
                                ref Dictionary <Body, CircleShape> bodyShapeMap, UpdateDelegate bodyPositionUpdater) : base(renderWindow, inputHandler)
        {
            this.bodies       = bodies;
            this.bodyShapeMap = bodyShapeMap;

            this.bodyPositionUpdater = bodyPositionUpdater;

            simulationDrawer       = new SimulationDrawer(renderWindow, ref this.bodies, ref this.bodyShapeMap);
            simulationInputHandler = (SimulationInputHandler)inputHandler;
            simulationInputHandler.SetSimulationDrawer(simulationDrawer);

            // constructs a new timer and attaches a timer event handler that updates the fps and window title every interval
            miscTimer = new Timer(TimerRefreshIntervalMs)
            {
                AutoReset = true, Enabled = true
            };
            miscTimer.Elapsed += (sender, args) =>
            {
                fps = framesElapsed / (TimerRefreshIntervalMs / 1000);

                framesElapsed = 0;
                renderWindow.SetTitle($"N-Body Simulator: FPS {fps}");
            };

            fileWriter = CreateFileWriter();
        }
Пример #34
0
 public string DispatchAction(IInputHandler inputHandler)
 {
     switch (inputHandler.ActionName)
     {
         case "RegisterUser":
             return this.Tracker.RegisterUser(
                 inputHandler.Parameters["username"],
                 inputHandler.Parameters["password"],
                 inputHandler.Parameters["confirmPassword"]);
         case "LoginUser":
             return this.Tracker.LoginUser(inputHandler.Parameters["username"], inputHandler.Parameters["password"]);
         case "LogoutUser":
             return this.Tracker.LogoutUser();
         case "CreateIssue":
             return this.Tracker.CreateIssue(
                 inputHandler.Parameters["title"],
                 inputHandler.Parameters["description"],
                 (IssuePriority)Enum.Parse(typeof(IssuePriority), inputHandler.Parameters["priority"], true),
                 inputHandler.Parameters["tags"].Split('|'));
         case "RemoveIssue":
             return this.Tracker.RemoveIssue(int.Parse(inputHandler.Parameters["id"]));
         case "AddComment":
             return this.Tracker.AddComment(int.Parse(inputHandler.Parameters["id"]), inputHandler.Parameters["text"]);
         case "MyIssues":
             return this.Tracker.GetMyIssues();
         case "MyComments":
             return this.Tracker.GetMyComments();
         case "Search":
             return this.Tracker.SearchForIssues(inputHandler.Parameters["tags"].Split('|'));
         default:
             return string.Format("Invalid action: {0}", inputHandler.ActionName);
     }
 }
Пример #35
0
 public Camera(Game game)
     : base(game)
 {
     graphics = (GraphicsDeviceManager)Game.Services.GetService(typeof(IGraphicsDeviceManager));
     input    = (IInputHandler)game.Services.GetService(typeof(IInputHandler));
     console  = (GameConsole)game.Services.GetService(typeof(IGameConsole));
 }
Пример #36
0
    // Update is called once per frame
    void Update()
    {
        var currentInput = new InputData();

        if (Input.GetKey(UpKey))
        {
            currentInput.MovementDirection |= InputData.Direction.Up;
        }
        if (Input.GetKey(DownKey))
        {
            currentInput.MovementDirection |= InputData.Direction.Down;
        }
        if (Input.GetKey(LeftKey))
        {
            currentInput.MovementDirection |= InputData.Direction.Left;
        }
        if (Input.GetKey(RightKey))
        {
            currentInput.MovementDirection |= InputData.Direction.Right;
        }

        currentInput.ActionButton = Input.GetKeyDown(ActionButton);
        CurrentHandler            = DefaultHandlerObject.GetInterface <IInputHandler>();

        if (CurrentHandler != null)
        {
            CurrentHandler.TakeInput(currentInput);
        }
    }
        public override void Initialize()
        {
            //Grab a reference to the IInputHandler service.
            InputHandler = GameServiceManager.GetService<IInputHandler>();

            base.Initialize();
        }
Пример #38
0
    public static void Push(IInputHandler parent, IInputHandler child)
    {
        KInputHandler inputHandler  = GetInputHandler(parent);
        KInputHandler inputHandler2 = GetInputHandler(child);

        inputHandler.PushInputHandler(inputHandler2);
    }
 public static void UnregisterHandler(IInputHandler handler)
 {
     if (handlers.Contains(handler))
     {
         handlers.Remove(handler);
     }
 }
Пример #40
0
        public void DrawRegions(WorldRenderer wr, IInputHandler inputHandler)
        {
            renderer.BeginFrame(scrollPosition, Zoom);
            if (wr != null)
            {
                wr.Draw();
            }

            using (new PerfSample("render_widgets"))
            {
                Ui.Draw();
                var cursorName     = Ui.Root.GetCursorOuter(Viewport.LastMousePos) ?? "default";
                var cursorSequence = CursorProvider.GetCursorSequence(cursorName);
                var cursorSprite   = cursorSequence.GetSprite((int)cursorFrame);

                renderer.SpriteRenderer.DrawSprite(cursorSprite,
                                                   Viewport.LastMousePos - cursorSequence.Hotspot,
                                                   Game.modData.Palette.GetPaletteIndex(cursorSequence.Palette),
                                                   cursorSprite.size);
            }

            using (new PerfSample("render_flip"))
            {
                renderer.EndFrame(inputHandler);
            }
        }
Пример #41
0
 internal static void Update(IInputHandler handler, InputDeviceButton input, bool value)
 {
     if (input.IsPressed != value)
     {
         input.IsPressed = value;
         handler.OnInput(input);
     }
 }
Пример #42
0
 internal static void Update(IInputHandler handler, InputDeviceAxis input, float value)
 {
     if (input.Value != value)
     {
         input.Value = value;
         handler.OnInput(input);
     }
 }
Пример #43
0
 public GameState(Game game)
     : base(game)
 {
     GameManager = (IGameStateManager)game.Services.GetService(
         typeof(IGameStateManager));
     Input = (IInputHandler)game.Services.GetService(
         typeof(IInputHandler));
 }
Пример #44
0
 public Camera(Game game)
     : base(game)
 {
     graphics = (GraphicsDeviceManager)Game.Services.GetService
      (typeof(IGraphicsDeviceManager));
     input = (IInputHandler)game.Services.GetService
      (typeof(IInputHandler));
 }
Пример #45
0
 /// <summary>
 /// Konstruktør for kube med gitt posisjon.
 /// </summary>
 /// <param name="game">Spillet</param>
 /// <param name="position">Kubens posisjon</param>
 public Cube(Game game, Vector3 position, Effect effect)
     : base(game)
 {
     // TODO: Construct any child components here
     input = (IInputHandler)Game.Services.GetService(typeof(IInputHandler));
     this.position = position;
     this.effect = effect;
 }
Пример #46
0
 public Game(IRenderer renderer, IInputHandler inputHandler, IBoardSetup boardSetupRules)
 {
     this.renderer = renderer;
     this.inputHandler = inputHandler;
     this.boardSetupRules = boardSetupRules;
     this.player = new Player();
     this.commandController = new CommandController(this.player);
 }
 public BookStoreEngine(IInputHandler inputHandler, IRenderer renderer)
 {
     this.IsRunning = true;
     this.books = new List<IBook>();
     this.revenue = 0;
     this.InputHandler = inputHandler;
     this.Renderer = renderer;
 }
Пример #48
0
 public GBSystem(IRenderable renderWindow, IInputHandler iInputHandler, ITimekeeper timeKeeper)
 {
     screen = renderWindow;
     state = GBSystemState.Stopped;
     isFocused = true;
     inputHandler = iInputHandler;
     frameTimer = timeKeeper;
     frameLimitIndex = 1;
 }
Пример #49
0
        public FishCam(Game game, Vector3 pos)
            : base(game)
        {
            graphics = (GraphicsDeviceManager)game.Services.GetService(typeof(IGraphicsDeviceManager));
            cameraPosition = pos;

            //Reference to the input handeler
            input = (IInputHandler)game.Services.GetService(typeof(IInputHandler));
        }
Пример #50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GameEngine" /> class.
        /// </summary>
        /// <param name="dependencies">An object which holds the dependencies for the game engine.</param>
        public GameEngine(GameEngineDependencies dependencies)
        {
            this.userInterface = dependencies.UserInterface;
            this.drawer = this.userInterface.Drawer;
            this.reader = this.userInterface.Reader;

            this.commandFactory = dependencies.CommandFactory;

            this.ctx = new CommandContext(dependencies.Logger, new Board(dependencies.Board.Rows, dependencies.Board.Cols, new RandomGenerator()), 0, 0, dependencies.BoardMemory, Highscore.GetInstance(), new HighscoreProcessor());
        }
Пример #51
0
        /// <summary> 
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            Graphics.PreferredBackBufferWidth = 1280;
            Graphics.PreferredBackBufferHeight = 720;
            Graphics.ApplyChanges();
            
            Components.Add(new FrameRateCounter(this, "Content\\debugfont", 1f));
            Components.Add(new GameObjectInfoDisplay(this, 5, "Content\\debugfont", new Vector2(0f, 25f)));

            ComponentFactory componentFactory = new ComponentFactory();
            TiledGameObjectFactory gameObjectFactory = new TiledGameObjectFactory(this.Content);
            gameObjectFactory.PathToXML = "EntityDefinitions\\entity.xml";
            
            inputHandler = new InputHandler(false);
            playerManager = new PlayerManager();

            particleManager = new ParticleManager(Content, "ParticleEffects\\", "Textures\\");

            PhysicsManager physicsManager = new PhysicsManager();
            particleRenderer = new SpriteBatchRenderer();
            particleRenderer.GraphicsDeviceService = Graphics;

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            renderer = new Renderer(Graphics, spriteBatch);
            renderer.SetInternalResolution(1280, 720);
            renderer.SetScreenResolution(1280, 720, false);

            GameServiceManager.AddService(typeof(IGameObjectFactory), gameObjectFactory);
            GameServiceManager.AddService(typeof(IComponentFactory), componentFactory);
            GameServiceManager.AddService(typeof(RenderableFactory), new RenderableFactory(this.Content));
            GameServiceManager.AddService(typeof(IInputHandler), inputHandler);
            GameServiceManager.AddService(typeof(PlayerManager), playerManager);
            GameServiceManager.AddService(typeof(IScoreManager), new ScoreManager());
            GameServiceManager.AddService(typeof(IGameObjectManager), new GameObjectManager());
            GameServiceManager.AddService(typeof(IPhysicsManager), physicsManager);
            GameServiceManager.AddService(typeof(IBehaviorFactory), new BehaviorFactory());
            GameServiceManager.AddService(typeof(IActionFactory), new ActionFactory());
            GameServiceManager.AddService(typeof(IActionManager), new ActionManager());
            GameServiceManager.AddService(typeof(ILevelLogicManager), new LevelLogicManager(this.Content));
            GameServiceManager.AddService(typeof(IRandomGenerator), new RandomGenerator());
            GameServiceManager.AddService(typeof(IParticleManager), particleManager);
            GameServiceManager.AddService(typeof(IRenderer), renderer);

            debugView = new DebugViewXNA(GameServiceManager.GetService<IPhysicsManager>().PhysicsWorld);

            //Initialize the GameServices
            GameServiceManager.Initialize();
            
            CameraController.Initialize(this);
            CameraController.MoveCamera(new Vector2(GraphicsDevice.Viewport.Width / 2f, GraphicsDevice.Viewport.Height / 2f));
            
            base.Initialize();
        }
Пример #52
0
 public void HandleInput(IInputHandler handler, float delta)
 {
     HandleInput(delta, handler.HandleKeyboardInput);
     #if !XBOX360
     HandleInput(delta, handler.HandleMouseInput);
     #endif
     HandleInput(delta, PlayerIndex.One, handler.HandleGamePadInput);
     HandleInput(delta, PlayerIndex.Two, handler.HandleGamePadInput);
     HandleInput(delta, PlayerIndex.Three, handler.HandleGamePadInput);
     HandleInput(delta, PlayerIndex.Four, handler.HandleGamePadInput);
 }
 public Engine(
     IInputHandler reader,
     IOutputRenderer writer, 
     IGameData gameData, 
     ICommandManager commandManager)
 {
     this.Reader = reader;
     this.Writer = writer;
     this.GameData = gameData;
     this.CommandManager = commandManager;
 }
Пример #54
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.IsFixedTimeStep = false;
            graphics.SynchronizeWithVerticalRetrace = false;
            //graphics.IsFullScreen = true;

            InputHandler tempHandler = new InputHandler(this);
            inputHandler = tempHandler;
            Components.Add(tempHandler);
        }
Пример #55
0
        public Bumpership(IInputHandler input, World world, object shape, string name, Vector spawnPosition)
        {
            this.input = input;
            this.world = world;
            Shape = shape;
            Name = name;
            this.spawnPosition = spawnPosition;

            Radius = 0.5;
            factor1 = 0.05;
            factor2 = 0.1;

            Spawn();
        }
Пример #56
0
        public Engine(IFovStrategy fovStrategy, ITileFactory tileFactory, World world, IInputHandler input, ILogController gameLog, ConsoleWindow console)
        {
            FovStrategy = fovStrategy;
            TileFactory = tileFactory;
            World = world;
            InputHandler = input;
            Console = console;

            if (ActorControllers == null)
            {
                ActorControllers = new List<IController>();
            }

            if (FurnitureControllers == null)
            {
                FurnitureControllers = new List<IController>();
            }

            GameLogController = gameLog;
        }
Пример #57
0
 private Bumpership CreateBumpership(PlayerType player, IInputHandler keyboardHandler, SocketManager socketManager, ref int countShip)
 {
     IInputHandler input;
     string name = "";
     switch (player)
     {
         case PlayerType.Human:
             input = keyboardHandler;
             name = "Human";
             break;
         case PlayerType.AI:
             input = socketManager.GetNetworkPlayer();
             break;
         default:
             input = new IdiotAi(); // Test
             break;
     }
     Vector startPosition = world.Map.StartPositions[countShip];
     countShip++;
     return new Bumpership(input, world, graphics.CreateShip(), name, startPosition);
 }
Пример #58
0
        public GameManager(
            GameSettings gameSettings,
            IInputHandler keyboardHandler,
            SocketManager socketManager,
            IGraphicsHandler graphics)
        {
            this.gameSettings = gameSettings;
            this.graphics = graphics;
            const int ticksPerSecond = 30;
            gameLoop = new GameLoop(5, ticksPerSecond);
            gameLoop.Update += Update;
            gameLoop.Render += Render;

            Map map = new Map(gameSettings.Map);
            world = new World(map);

            int countShip = 0;
            List<Bumpership> bumperships = gameSettings.Players.Take(world.Map.StartPositions.Count)
                .Select(p => CreateBumpership(p, keyboardHandler, socketManager, ref countShip))
                .ToList();
            world.AddShips(bumperships);
        }
Пример #59
0
        public void PumpInput(IInputHandler inputHandler)
        {
            Game.HasInputFocus = 0 != (Sdl.SDL_GetAppState() & Sdl.SDL_APPINPUTFOCUS);

            var mods = MakeModifiers(Sdl.SDL_GetModState());
            inputHandler.ModifierKeys(mods);
            MouseInput? pendingMotion = null;

            Sdl.SDL_Event e;
            while (Sdl.SDL_PollEvent(out e) != 0)
            {
                switch (e.type)
                {
                case Sdl.SDL_QUIT:
                    OpenRA.Game.Exit();
                    break;

                case Sdl.SDL_MOUSEBUTTONDOWN:
                    {
                        if (pendingMotion != null)
                        {
                            inputHandler.OnMouseInput(pendingMotion.Value);
                            pendingMotion = null;
                        }

                        var button = MakeButton(e.button.button);
                        lastButtonBits |= button;

                        var pos = new int2(e.button.x, e.button.y);

                        inputHandler.OnMouseInput(new MouseInput(
                            MouseInputEvent.Down, button, pos, mods,
                            MultiTapDetection.DetectFromMouse(e.button.button, pos)));

                        break;
                    }

                case Sdl.SDL_MOUSEBUTTONUP:
                    {
                        if (pendingMotion != null)
                        {
                            inputHandler.OnMouseInput(pendingMotion.Value);
                            pendingMotion = null;
                        }

                        var button = MakeButton(e.button.button);
                        lastButtonBits &= ~button;

                        var pos = new int2(e.button.x, e.button.y);
                        inputHandler.OnMouseInput(new MouseInput(
                            MouseInputEvent.Up, button, pos, mods,
                            MultiTapDetection.InfoFromMouse(e.button.button)));

                        break;
                    }

                case Sdl.SDL_MOUSEMOTION:
                    {
                        pendingMotion = new MouseInput(
                            MouseInputEvent.Move, lastButtonBits,
                            new int2(e.motion.x, e.motion.y), mods, 0);

                        break;
                    }

                case Sdl.SDL_KEYDOWN:
                    {
                        var keyName = Sdl.SDL_GetKeyName(e.key.keysym.sym);

                        var keyEvent = new KeyInput
                        {
                            Event = KeyInputEvent.Down,
                            Modifiers = mods,
                            UnicodeChar = (char)e.key.keysym.unicode,
                            KeyName = Sdl.SDL_GetKeyName(e.key.keysym.sym),
                            VirtKey = e.key.keysym.sym,
                            MultiTapCount = MultiTapDetection.DetectFromKeyboard(keyName)
                        };

                        // Special case workaround for windows users
                        if (e.key.keysym.sym == Sdl.SDLK_F4 && mods.HasModifier(Modifiers.Alt) &&
                            Platform.CurrentPlatform == PlatformType.Windows)
                        {
                            OpenRA.Game.Exit();
                        }
                        else
                            inputHandler.OnKeyInput(keyEvent);

                        break;
                    }

                case Sdl.SDL_KEYUP:
                    {
                        var keyName = Sdl.SDL_GetKeyName(e.key.keysym.sym);
                        var keyEvent = new KeyInput
                        {
                            Event = KeyInputEvent.Up,
                            Modifiers = mods,
                            UnicodeChar = (char)e.key.keysym.unicode,
                            KeyName = Sdl.SDL_GetKeyName(e.key.keysym.sym),
                            VirtKey = e.key.keysym.sym,
                            MultiTapCount = MultiTapDetection.InfoFromKeyboard(keyName)
                        };

                        inputHandler.OnKeyInput(keyEvent);
                        break;
                    }
                }
            }

            if (pendingMotion != null)
            {
                inputHandler.OnMouseInput(pendingMotion.Value);
                pendingMotion = null;
            }

            ErrorHandler.CheckGlError();
        }
Пример #60
0
		public void PumpInput(IInputHandler inputHandler)
		{
			var mods = MakeModifiers((int)SDL.SDL_GetModState());
			var scrollDelta = 0;
			inputHandler.ModifierKeys(mods);
			MouseInput? pendingMotion = null;

			SDL.SDL_Event e;
			while (SDL.SDL_PollEvent(out e) != 0)
			{
				switch (e.type)
				{
					case SDL.SDL_EventType.SDL_QUIT:
						Game.Exit();
						break;

					case SDL.SDL_EventType.SDL_WINDOWEVENT:
					{
						switch (e.window.windowEvent)
						{
							case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST:
								Game.HasInputFocus = false;
								break;

							case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED:
								Game.HasInputFocus = true;
								break;
						}

						break;
					}

					case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
					{
						if (pendingMotion != null)
						{
							inputHandler.OnMouseInput(pendingMotion.Value);
							pendingMotion = null;
						}

						var button = MakeButton(e.button.button);
						lastButtonBits |= button;

						var pos = new int2(e.button.x, e.button.y);

						inputHandler.OnMouseInput(new MouseInput(
							MouseInputEvent.Down, button, scrollDelta, pos, mods,
							MultiTapDetection.DetectFromMouse(e.button.button, pos)));

						break;
					}

					case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
					{
						if (pendingMotion != null)
						{
							inputHandler.OnMouseInput(pendingMotion.Value);
							pendingMotion = null;
						}

						var button = MakeButton(e.button.button);
						lastButtonBits &= ~button;

						var pos = new int2(e.button.x, e.button.y);
						inputHandler.OnMouseInput(new MouseInput(
							MouseInputEvent.Up, button, scrollDelta, pos, mods,
							MultiTapDetection.InfoFromMouse(e.button.button)));

						break;
					}

					case SDL.SDL_EventType.SDL_MOUSEMOTION:
					{
						pendingMotion = new MouseInput(
							MouseInputEvent.Move, lastButtonBits, scrollDelta,
							new int2(e.motion.x, e.motion.y), mods, 0);

						break;
					}

					case SDL.SDL_EventType.SDL_MOUSEWHEEL:
					{
						int x, y;
						SDL.SDL_GetMouseState(out x, out y);
						scrollDelta = e.wheel.y;
						inputHandler.OnMouseInput(new MouseInput(MouseInputEvent.Scroll, MouseButton.None, scrollDelta, new int2(x, y), Modifiers.None, 0));

						break;
					}

					case SDL.SDL_EventType.SDL_TEXTINPUT:
					{
						string input;
						unsafe
						{
							var data = new byte[SDL.SDL_TEXTINPUTEVENT_TEXT_SIZE];
							var i = 0;
							for (; i < SDL.SDL_TEXTINPUTEVENT_TEXT_SIZE; i++)
							{
								var b = e.text.text[i];
								if (b == '\0')
									break;

								data[i] = b;
							}

							input = Encoding.UTF8.GetString(data, 0, i);
						}

						inputHandler.OnTextInput(input);
						break;
					}

					case SDL.SDL_EventType.SDL_KEYDOWN:
					case SDL.SDL_EventType.SDL_KEYUP:
					{
						var keyCode = (Keycode)e.key.keysym.sym;
						var type = e.type == SDL.SDL_EventType.SDL_KEYDOWN ?
							KeyInputEvent.Down : KeyInputEvent.Up;

						var tapCount = e.type == SDL.SDL_EventType.SDL_KEYDOWN ?
							MultiTapDetection.DetectFromKeyboard(keyCode) :
							MultiTapDetection.InfoFromKeyboard(keyCode);

						var keyEvent = new KeyInput
						{
							Event = type,
							Key = keyCode,
							Modifiers = mods,
							UnicodeChar = (char)e.key.keysym.sym,
							MultiTapCount = tapCount
						};

						// Special case workaround for windows users
						if (e.key.keysym.sym == SDL.SDL_Keycode.SDLK_F4 && mods.HasModifier(Modifiers.Alt) &&
							Platform.CurrentPlatform == PlatformType.Windows)
							Game.Exit();
						else
							inputHandler.OnKeyInput(keyEvent);

						break;
					}
				}
			}

			if (pendingMotion != null)
			{
				inputHandler.OnMouseInput(pendingMotion.Value);
				pendingMotion = null;
			}

			ErrorHandler.CheckGlError();
		}