A screen is a single layer that has update and draw logic, and which can be combined with other layers to build up a complex menu system. For instance the main menu, the options menu, the "are you sure you want to quit" message box, and the main game itself are all implemented as screens.
Example #1
1
		/// <summary>
		/// The constructor is private: loading screens should
		/// be activated via the static Load method instead.
		/// </summary>
		private LoadingScreen (ScreenManager screenManager,bool loadingIsSlow, 
				GameScreen[] screensToLoad)
			{
			this.loadingIsSlow = loadingIsSlow;
			this.screensToLoad = screensToLoad;

			TransitionOnTime = TimeSpan.FromSeconds (0.5);

			// If this is going to be a slow load operation, create a background
			// thread that will update the network session and draw the load screen
			// animation while the load is taking place.
			if (loadingIsSlow) {
				backgroundThread = new Thread (BackgroundWorkerThread);
				backgroundThreadExit = new ManualResetEvent (false);

				graphicsDevice = screenManager.GraphicsDevice;

				// Look up some services that will be used by the background thread.
				IServiceProvider services = screenManager.Game.Services;

				networkSession = (NetworkSession)services.GetService (
							typeof(NetworkSession));

				messageDisplay = (IMessageDisplay)services.GetService (
							typeof(IMessageDisplay));
			}
		}
 public SongSelectionBox(GameScreen screen, Vector2 position, Vector2 size)
     : base(screen.ScreenManager.Game)
 {
     this.screen = screen;
     this.position = position;
     this.size = size;
 }
Example #3
0
 public Widget(GameScreen screen, ContentManager content)
 {
     Screen = screen;
     spriteBatch = screen.ScreenManager.SpriteBatch;
     contentManager = content;
     LoadContent();
 }
Example #4
0
 // this is not a permanent solution!
 public static void LoadModScripts(GameScreen gameScreen, string dir)
 {
     foreach (string filename in Directory.GetFiles(dir))
     {
         if (filename.EndsWith(".fazemod"))
         {
             bool add = false;   // add this script to screen or not?
             Script scriptToAdd = GetScriptFromAssembly(filename);
             // we have got the script and it's initialized, but is it the one we want?
             if (scriptToAdd.SupportedScreenTypes != null)
             {
                 foreach (Type type in scriptToAdd.SupportedScreenTypes)
                     if (type == gameScreen.GetType()) add = true;
             }
             else
                 add = true;
             if (add)
             {
                 scriptToAdd.GameScreen = gameScreen;
                 scriptToAdd.FileName = Path.GetFileName(filename);
                 gameScreen.Scripts.Add(scriptToAdd);
                 scriptToAdd.Init(); // dont forget to init them
             }
         }
     }
 }
Example #5
0
        public PauseScreen(GameScreen backgroundScreen, Player human, Player computer)
            : base(String.Empty)
        {
            IsPopup = true;

            this.backgroundScreen = backgroundScreen;

            // Create our menu entries.
            MenuEntry startGameMenuEntry = new MenuEntry("Return");
            MenuEntry exitMenuEntry = new MenuEntry("Quit Game");

            // Hook up menu event handlers.
            startGameMenuEntry.Selected += StartGameMenuEntrySelected;
            exitMenuEntry.Selected += OnCancel;

            // Add entries to the menu.
            MenuEntries.Add(startGameMenuEntry);
            MenuEntries.Add(exitMenuEntry);

            this.human = human;
            this.computer = computer;

            // Preserve the old state of the game
            prevHumanIsActive = this.human.Catapult.IsActive;
            prevCompuerIsActive = this.computer.Catapult.IsActive;

            // Pause the game logic progress
            this.human.Catapult.IsActive = false;
            this.computer.Catapult.IsActive = false;

            AudioManager.PauseResumeSounds(false);
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public StoryScreen( List<String> storytext, List<String> titletext, GameScreen DestScreen, GameData saveData)
            : base(titletext[0])
        {
            saveGameData = saveData;
            this.DestScreen = DestScreen;

            //SpriteFont font = ScreenManager.Font; //Get font of the ScreenManager
            // Create our menu entries.
            Storyline = storytext;
            StoryTitles = titletext;

            StorylineEntry = new VarSizeMenuEntry ( Storyline[0] , 0.7f);
            BlankEntry = new VarSizeMenuEntry ( " ", 0.7f);
            MenuEntry ContinueEntry = new VarSizeMenuEntry ( "Continue", 1f);

            // Hook up menu event handlers.
            ContinueEntry.Selected += continueSelected;

            // Add entries to the menu.
            MenuEntries.Add ( StorylineEntry );
            MenuEntries.Add ( BlankEntry );
            MenuEntries.Add ( ContinueEntry );

            //Select the first selectable entry
            while (menuEntries[selectedEntry].HasNoHandle)
            {
                selectedEntry++;
            }
        }
Example #7
0
        // System.Drawing is NOT avaiable on WP7 or Xbox
        /*
         * http://stackoverflow.com/a/7394185/195722
         *
         *
         *
         */
        public static Texture2D GetTexture(this System.Drawing.Bitmap bitmap, GameScreen gameScreen)
        {
            BlendState oldstate = gameScreen.ScreenManager.GraphicsDevice.BlendState;
            gameScreen.ScreenManager.GraphicsDevice.BlendState = BlendState.AlphaBlend;
            Texture2D tex = new Texture2D(gameScreen.ScreenManager.GraphicsDevice, bitmap.Width, bitmap.Height, true, SurfaceFormat.Color);

            System.Drawing.Imaging.BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);

            int bufferSize = data.Height * data.Stride;

            //create data buffer
            byte[] bytes = new byte[bufferSize];

            // copy bitmap data into buffer
            System.Runtime.InteropServices.Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

            // copy our buffer to the texture
            tex.SetData(bytes);

            // unlock the bitmap data
            bitmap.UnlockBits(data);

            gameScreen.ScreenManager.GraphicsDevice.BlendState = oldstate;
            return tex;
        }
Example #8
0
 public Scenario(GameScreen gameScreen, GameWorld world, Camera2D camera)
     : base(gameScreen, world, camera)
 {
     levelNumber = 0;
     physics.bodys = new Body[1]{ new Body(world) };
     images = new List<SpriteSheet>();
 }
Example #9
0
        /// <summary>
        /// The constructor is private: loading screens should
        /// be activated via the static Load method instead.
        /// </summary>
        private LoadingScreen(ScreenManager screenManager, bool loadingIsSlow,
                              GameScreen[] screensToLoad)
        {
            this.loadingIsSlow = loadingIsSlow;
            this.screensToLoad = screensToLoad;

            TransitionOnTime = TimeSpan.FromSeconds(0.5);
        }
Example #10
0
        public void Draw(GameScreen screen)
        {
            // Grab some common items from the ScreenManager
            SpriteBatch spriteBatch = screen.ScreenManager.SpriteBatch;
            SpriteFont font = screen.ScreenManager.Font;

            spriteBatch.DrawString(font, Text, Position, Microsoft.Xna.Framework.Color.Yellow);
        }
Example #11
0
        public void AddScreen(GameScreen screen)
        {
            screen.ScreenManager = this;
            screen.IsExiting = false;

            if (isInitialized)
                screen.Activate(false);
            screens.Add(screen);
        }
        /// <summary>
        /// The constructor is private: loading screens should
        /// be activated via the static Load method instead.
        /// </summary>
        private LoadingScreen(ScreenManager screenManager, bool loadingIsSlow,
                              GameScreen[] screensToLoad)
            : base(false)
        {
            this.loadingIsSlow = loadingIsSlow;
            this.screensToLoad = screensToLoad;

            EnabledGestures = GestureType.Tap; // Monogame goes on an infinite loop if I don't do this..
        }
Example #13
0
        public PhysicObject(GameScreen gameScreen, GameWorld world, Camera2D camera)
            : base(gameScreen.ScreenManager.Game)
        {
            this.gameScreen = gameScreen;

            physics.world = world;
            physics.bodys = null;

            this.camera = camera;
        }
Example #14
0
 /// <summary>
 /// Constructs a new menu entry with the specified text.
 /// </summary>
 public MenuButton(Texture2D sprite, bool flip, Vector2 position, GameScreen screen)
 {
     _screen = screen;
     _scale = 1f;
     _sprite = sprite;
     _baseOrigin = new Vector2(_sprite.Width / 2f, _sprite.Height / 2f);
     _hover = false;
     _flip = flip;
     Position = position;
 }
Example #15
0
        /// <summary>
        /// The constructor is private: loading screens should
        /// be activated via the static Load method instead.
        /// </summary>
        private LoadingScreen(ScreenManager screenManager, bool loadingIsSlow,
                              GameScreen[] screensToLoad)
        {
            this.loadingIsSlow = loadingIsSlow;
            this.screensToLoad = screensToLoad;

             rnd = new Random();
             randInt = rnd.Next(3); // 0 to 2

            TransitionOnTime = TimeSpan.FromSeconds(0.5);
        }
Example #16
0
        public override void Draw(GameScreen screen, bool isSelected, GameTime gameTime)
        {
            ScreenManager screenManager = screen.ScreenManager;
            SpriteBatch spriteBatch = screenManager.SpriteBatch;
            GraphicsDevice graphics = screenManager.GraphicsDevice;

            outline.Location = position;
            outline.Width = (graphics.Viewport.Width / 45);
            outline.Height = (graphics.Viewport.Width / 10);

            spriteBatch.Draw(icon, outline, Color.White);
        }
Example #17
0
        public override void Draw(GameScreen screen, bool isSelected, Microsoft.Xna.Framework.GameTime gameTime)
        {
            ScreenManager screenManager = screen.ScreenManager;
            SpriteBatch spriteBatch = screenManager.SpriteBatch;
            GraphicsDevice graphics = screenManager.GraphicsDevice;

            outline.Location = position;
            outline.Width = ((graphics.PresentationParameters.BackBufferWidth / 45) * 14);
            outline.Height = (graphics.Viewport.Width / 30);

            spriteBatch.Draw(icon, outline, Color.SkyBlue);
        }
Example #18
0
        public Player(GameScreen gameScreen, GameWorld world, Camera2D camera)
            : base(gameScreen, world, camera)
        {
            rightwheelContacts = 0;
            leftwheelContacts = 0;
            jumpedTime = 0f;
            lookingLeft = false;
            timeOnAir = 0f;
            moving = false;

            resetNTImpulses();
        }
Example #19
0
        /// <summary>
        /// The constructor is private: loading screens should
        /// be activated via the static Load method instead.
        /// </summary>
        private LoadingScreen(ScreenManager screenManager, bool loadingIsSlow,
            GameScreen[] screensToLoad)
        {
            this.loadingIsSlow = loadingIsSlow;
            this.screensToLoad = screensToLoad;

            // we don't serialize loading screens. if the user exits while the
            // game is at a loading screen, the game will resume at the screen
            // before the loading screen.
            IsSerializable = false;

            TransitionOnTime = TimeSpan.FromSeconds(0.5);
        }
Example #20
0
        /// <summary>
        ///   Adds a new screen to the screen manager.
        /// </summary>
        public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
        {
            screen.ControllingPlayer = controllingPlayer;
            screen.ScreenManager = this;
            screen.IsExiting = false;

            // If we have a graphics device, tell the screen to load content.
            if (_isInitialized) {
                screen.LoadContent();
            }

            screens.Add(screen);

            // update the TouchPanel to respond to gestures this screen is interested in
            TouchPanel.EnabledGestures = screen.EnabledGestures;
        }
Example #21
0
        public Collectible(GameScreen gameScreen, Shape shape, World world, Camera2D camera)
            : base(gameScreen.ScreenManager.Game)
        {
            this.gameScreen = gameScreen;

            this.world = world;
            body = new Body(world);
            body.CreateFixture(shape);
            body.CollisionCategories = Category.Cat3;
            body.CollidesWith = Category.Cat2;
            body.BodyType = BodyType.Kinematic;

            body.OnCollision += body_OnCollision;

            shootParticles = false;
            collected = false;

            this.camera = camera;
        }
Example #22
0
        public MusicSelectionScreen(GameScreen backgroundScreen)
            : base("Main")
        {
            IsPopup = true;

            this.backgroundScreen = backgroundScreen;

            // Get the default media source
            mediaSourcesList = MediaSource.GetAvailableMediaSources();

            // Use only first one
            mediaLibrary = new MediaLibrary(mediaSourcesList[0]);

            // Create maximum 5 entries with music from music collection
            for (int i = 0; i < mediaLibrary.Songs.Count; i++)
            {
                if (i == 5)
                    break;

                Song song = mediaLibrary.Songs[i];

                // Create menu entry for the song.
                MenuEntry songMenuEntry = new MenuEntry(song.Name);
                // Hook up menu event handler
                songMenuEntry.Selected += OnSongSelected;
                // Add song to the menu
                MenuEntries.Add(songMenuEntry);
            }

            // Create our menu entries.
            MenuEntry cancelMenuEntry = new MenuEntry("Cancel");

            // Hook up menu event handlers.
            cancelMenuEntry.Selected += OnCancel;

            // Add entries to the menu.
            MenuEntries.Add(cancelMenuEntry);
        }
Example #23
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public PauseMenuScreen(GameScreen g)
            : base("Paused")
        {
            // Flag that there is no need for the game to transition
            // off when the pause menu is on top of it.
            IsPopup = true;

            source = g;

            // Create our menu entries.
            MenuEntry resumeGameMenuEntry = new MenuEntry("Resume Game");
            MenuEntry switchAirplaneMenuEntry = new MenuEntry("Switch airplanes");
            MenuEntry quitGameMenuEntry = new MenuEntry("Quit Game");

            // Hook up menu event handlers.
            resumeGameMenuEntry.Selected += OnCancel;
            quitGameMenuEntry.Selected += QuitGameMenuEntrySelected;
            switchAirplaneMenuEntry.Selected += SwitchAirplaneMenuEntrySelected;

            // Add entries to the menu.
            MenuEntries.Add(resumeGameMenuEntry);
            MenuEntries.Add(switchAirplaneMenuEntry);
            MenuEntries.Add(quitGameMenuEntry);
        }
        /// <summary>
        /// Removes a screen from the screen manager. You should normally
        /// use GameScreen.ExitScreen instead of calling this directly, so
        /// the screen can gradually transition off rather than just being
        /// instantly removed.
        /// </summary>
        public void RemoveScreen(GameScreen screen)
        {
            // If we have a graphics device, tell the screen to unload content.
            if (isInitialized)
            {
                screen.UnloadContent();
            }

            screens.Remove(screen);
            screensToUpdate.Remove(screen);

            // if there is a screen still in the manager, update TouchPanel
            // to respond to gestures that screen is interested in.
            if (screens.Count > 0)
            {
                TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures;
            }
        }
Example #25
0
        /// <summary>
        /// Allows each screen to run logic.
        /// </summary>
        public override void Update(GameTime gameTime)
        {
            UpdateTouchPanelSize();

            // Read the keyboard and gamepad.
            if (!SuppressInputUpdate)
            {
                _input.Update(gameTime);
            }
            SuppressInputUpdate = false;

            // Make a copy of the master screen list, to avoid confusion if
            // the process of updating one screen adds or removes others.
            _tempScreensList.Clear();

            foreach (GameScreen screen in _screens)
            {
                _tempScreensList.Add(screen);
            }

            bool otherScreenHasFocus  = !Game.IsActive;
            bool coveredByOtherScreen = false;

            // Loop as long as there are screens waiting to be updated.
            while (_tempScreensList.Count > 0)
            {
                // Pop the topmost screen off the waiting list.
                GameScreen screen = _tempScreensList[_tempScreensList.Count - 1];

                _tempScreensList.RemoveAt(_tempScreensList.Count - 1);

                // Update the screen.
                screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

                if (screen.ScreenState == ScreenState.TransitionOn ||
                    screen.ScreenState == ScreenState.Active)
                {
                    // If this is the first active screen we came across,
                    // give it a chance to handle input.
                    if (!otherScreenHasFocus)
                    {
                        screen.HandleInput(gameTime, _input);

                        otherScreenHasFocus = true;
                    }

                    // If this is an active non-popup, inform any subsequent
                    // screens that they are covered by it.
                    if (!screen.IsPopup)
                    {
                        coveredByOtherScreen = true;
                    }
                }
            }

            ScrollableGame.End();

            // Print debug trace?
            if (_traceEnabled)
            {
                TraceScreens();
            }
        }
Example #26
0
        /// <summary>
        /// Adds a new screen to the screen manager.
        /// </summary>
        public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
        {
            screen.ControllingPlayer = controllingPlayer;
            screen.ScreenManager = this;
            screen.IsExiting = false;

            // If we have a graphics device, tell the screen to load content.
            if (isInitialized)
            {
                screen.Activate(false);
            }

            screens.Add(screen);
        }
Example #27
0
        public bool Activate(bool instancePreserved)
#endif
        {
#if !WINDOWS_PHONE && !WINDOWS && !ANDROID
            return(false);
#else
            // If the game instance was preserved, the game wasn't dehydrated so our screens still exist.
            // We just need to activate them and we're ready to go.
            if (instancePreserved)
            {
                // Make a copy of the master screen list, to avoid confusion if
                // the process of activating one screen adds or removes others.
                _tempScreensList.Clear();

                foreach (GameScreen screen in _screens)
                {
                    _tempScreensList.Add(screen);
                }

                foreach (GameScreen screen in _tempScreensList)
                {
                    screen.Activate(true);
                }
            }

            // Otherwise we need to refer to our saved file and reconstruct the screens that were present
            // when the game was deactivated.
            else
            {
                // Try to get the screen factory from the services, which is required to recreate the screens
                var screenFactory = Game.Services.GetService(typeof(IScreenFactory)) as IScreenFactory;
                if (screenFactory == null)
                {
                    throw new InvalidOperationException(
                              "Game.Services must contain an IScreenFactory in order to activate the ScreenManager.");
                }

#if WINDOWS8
                StorageFolder folder = ApplicationData.Current.LocalFolder;
                try
                {
                    using (Stream file = await folder.OpenStreamForReadAsync(StateFilename))
                    {
#else
                // Open up isolated storage
                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // Check for the file; if it doesn't exist we can't restore state
                    if (!storage.FileExists(StateFilename))
                    {
                        return(false);
                    }

                    // Read the state file so we can build up our screens
                    using (IsolatedStorageFileStream file = storage.OpenFile(StateFilename, FileMode.Open))
                    {
#endif
                        XDocument doc = XDocument.Load(file);

                        // Iterate the document to recreate the screen stack
                        foreach (XElement screenElem in doc.Root.Elements("GameScreen"))
                        {
                            // Use the factory to create the screen
                            Type       screenType = Type.GetType(screenElem.Attribute("Type").Value);
                            GameScreen screen     = screenFactory.CreateScreen(screenType);

                            if (screen != null)
                            {
                                // Add the screen to the screens list and activate the screen
                                screen.ScreenManager = this;
                                _screens.Add(screen);

                                if (screen.content == null)
                                {
                                    screen.content = new ContentManager(Game.Services, Game.Content.RootDirectory);
                                }
                                screen.Activate(false);

                                // update the TouchPanel to respond to gestures this screen is interested in
                                TouchPanel.EnabledGestures = screen.EnabledGestures;
                            }
                        }
                    }
                }
#if WINDOWS8
                catch (FileNotFoundException)
                {
                    return(false);
                }
#endif
            }

            return(true);
#endif
        }
Example #28
0
 public static void Load(GameScreen gameScreen, PrefabType prefabType)
 {
     if(textures.ContainsKey(prefabType))
         return;
     textures.Add(prefabType, gameScreen.Load<Texture2D>(GetTextureName(prefabType)));
 }
Example #29
0
        /// <summary>
        /// Removes a screen from the screen manager. You should normally
        /// use GameScreen.ExitScreen instead of calling this directly, so
        /// the screen can gradually transition off rather than just being
        /// instantly removed.
        /// </summary>
        public void RemoveScreen(GameScreen screen)
        {
            // If we have a graphics device, tell the screen to unload content.
            if (isInitialized)
            {
                screen.Unload();
            }

            screens.Remove(screen);
            tempScreensList.Remove(screen);
        }
Example #30
0
        /// <summary>
        /// Removes a screen from the screen manager. You should normally
        /// use GameScreen.ExitScreen instead of calling this directly, so
        /// the screen can gradually transition off rather than just being
        /// instantly removed.
        /// </summary>
        public void RemoveScreen(GameScreen screen)
        {
            // If we have a graphics device, tell the screen to unload content.
            if (isInitialized)
            {
                screen.UnloadContent();
            }

            screens.Remove(screen);
            screensToUpdate.Remove(screen);
        }
Example #31
0
        /// <summary>
        /// Draws the UIElement. This should be called by other elements and not overriden
        /// </summary>
        /// <param name="screen">The screen drawing the button</param>
        public void Draw(GameScreen screen, GameTime gameTime, SpriteBatch spriteBatch, SpriteDrawer spriteDrawer)
        {
            if (!Visible) {
                // element is not visible. don't draw it
                return;
            }

            MyScreen = screen;
            MyScreenManager = screen.ScreenManager;
            MyGameTime = gameTime;
            MySpriteBatch = spriteBatch;
            MySpriteDrawer = spriteDrawer;

            // can set more properties to the screen like opacity/overlay here
            // also can set boundries to not allow drawthis to drow outside the given size and position
            DrawThis();
        }
Example #32
0
        /// <summary>
        /// Draws the button
        /// </summary>
        /// <param name="screen">The screen drawing the button</param>
        public void Draw(GameScreen screen)
        {
            // Grab some common items from the ScreenManager
            SpriteBatch spriteBatch = screen.ScreenManager.SpriteBatch;
            SpriteFont font = screen.ScreenManager.Font;
            Texture2D blank = screen.ScreenManager.BlankTexture;

            // Compute the button's rectangle
            Rectangle r = new Rectangle(
                (int)Position.X,
                (int)Position.Y,
                (int)Size.X,
                (int)Size.Y);

            // Fill the button
            spriteBatch.Draw(blank, r, FillColor * Alpha);

            // Draw the border
            spriteBatch.Draw(
                blank,
                new Rectangle(r.Left, r.Top, r.Width, BorderThickness),
                BorderColor * Alpha);
            spriteBatch.Draw(
                blank,
                new Rectangle(r.Left, r.Top, BorderThickness, r.Height),
                BorderColor * Alpha);
            spriteBatch.Draw(
                blank,
                new Rectangle(r.Right - BorderThickness, r.Top, BorderThickness, r.Height),
                BorderColor * Alpha);
            spriteBatch.Draw(
                blank,
                new Rectangle(r.Left, r.Bottom - BorderThickness, r.Width, BorderThickness),
                BorderColor * Alpha);

            // Draw the text centered in the button
            Vector2 textSize = font.MeasureString(Text);
            Vector2 textPosition = new Vector2(r.Center.X, r.Center.Y) - textSize / 2f;
            textPosition.X = (int)textPosition.X;
            textPosition.Y = (int)textPosition.Y;
            spriteBatch.DrawString(font, Text, textPosition, TextColor * Alpha);
        }
Example #33
0
        public bool DeserializeState()
        {
            // open up isolated storage
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // see if our saved state directory exists
                if (storage.DirectoryExists("ScreenManager"))
                {
                    try
                    {
                        // see if we have a screen list
                        if (storage.FileExists("ScreenManager\\ScreenList.dat"))
                        {
                            // load the list of screen types
                            using (IsolatedStorageFileStream stream =
                                       storage.OpenFile("ScreenManager\\ScreenList.dat", FileMode.Open,
                                                        FileAccess.Read))
                            {
                                using (BinaryReader reader = new BinaryReader(stream))
                                {
                                    while (reader.BaseStream.Position < reader.BaseStream.Length)
                                    {
                                        // read a line from our file
                                        string line = reader.ReadString();

                                        // if it isn't blank, we can create a screen from it
                                        if (!string.IsNullOrEmpty(line))
                                        {
                                            Type       screenType = Type.GetType(line);
                                            GameScreen screen     = Activator.CreateInstance(screenType) as GameScreen;
                                            AddScreen(screen, PlayerIndex.One);
                                        }
                                    }
                                }
                            }
                        }

                        // next we give each screen a chance to deserialize from the disk
                        for (int i = 0; i < screens.Count; i++)
                        {
                            string filename = string.Format("ScreenManager\\Screen{0}.dat", i);
                            using (IsolatedStorageFileStream stream = storage.OpenFile(filename,
                                                                                       FileMode.Open, FileAccess.Read))
                            {
                                screens[i].Deserialize(stream);
                            }
                        }

                        return(true);
                    }
                    catch (Exception)
                    {
                        // if an exception was thrown while reading, odds are we cannot recover
                        // from the saved state, so we will delete it so the game can correctly
                        // launch.
                        DeleteState(storage);
                    }
                }
            }

            return(false);
        }
Example #34
0
        public bool Activate(bool instancePreserved)
        {
#if !WINDOWS_PHONE
            return(false);
#else
            // If the game instance was preserved, the game wasn't dehydrated so our screens still exist.
            // We just need to activate them and we're ready to go.
            if (instancePreserved)
            {
                // Make a copy of the master screen list, to avoid confusion if
                // the process of activating one screen adds or removes others.
                tempScreensList.Clear();

                foreach (GameScreen screen in screens)
                {
                    tempScreensList.Add(screen);
                }

                foreach (GameScreen screen in tempScreensList)
                {
                    screen.Activate(true);
                }
            }

            // Otherwise we need to refer to our saved file and reconstruct the screens that were present
            // when the game was deactivated.
            else
            {
                // Try to get the screen factory from the services, which is required to recreate the screens
                IScreenFactory screenFactory = Game.Services.GetService(typeof(IScreenFactory)) as IScreenFactory;
                if (screenFactory == null)
                {
                    throw new InvalidOperationException(
                              "Game.Services must contain an IScreenFactory in order to activate the ScreenManager.");
                }

                // Open up isolated storage
                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // Check for the file; if it doesn't exist we can't restore state
                    if (!storage.FileExists(StateFilename))
                    {
                        return(false);
                    }

                    // Read the state file so we can build up our screens
                    using (IsolatedStorageFileStream stream = storage.OpenFile(StateFilename, FileMode.Open))
                    {
                        XDocument doc = XDocument.Load(stream);

                        // Iterate the document to recreate the screen stack
                        foreach (XElement screenElem in doc.Root.Elements("GameScreen"))
                        {
                            // Use the factory to create the screen
                            Type       screenType = Type.GetType(screenElem.Attribute("Type").Value);
                            GameScreen screen     = screenFactory.CreateScreen(screenType);

                            // Rehydrate the controlling player for the screen
                            PlayerIndex?controllingPlayer = screenElem.Attribute("ControllingPlayer").Value != ""
                                ? (PlayerIndex)Enum.Parse(typeof(PlayerIndex), screenElem.Attribute("ControllingPlayer").Value, true)
                                : (PlayerIndex?)null;
                            screen.ControllingPlayer = controllingPlayer;

                            // Add the screen to the screens list and activate the screen
                            screen.ScreenManager = this;
                            screens.Add(screen);
                            screen.Activate(false);

                            // update the TouchPanel to respond to gestures this screen is interested in
                            TouchPanel.EnabledGestures = screen.EnabledGestures;
                        }
                    }
                }
            }

            return(true);
#endif
        }