Sign in to follow this  
xtheendx

XNA Platformer Game State Management Error

Recommended Posts

xtheendx    127
When calling ScreenManager (ScreenManager screenManager = new ScreenManager(game);) and ContentManager (ContentManager Content = new ContentManager(game);) and placing game in their parameters I am getting the error 'game' does not exist in the current context. First is game the correct parameter, I am pretty sure it is as it is the parameter in the ScreenManager constructor. And if it is in fact correct, how do I make in exist in the current context. here is ScreenManger code:
#region File Description
//-----------------------------------------------------------------------------
// ScreenManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
#endregion

namespace Platformer1
{
    /// <summary>
    /// The screen manager is a component which manages one or more GameScreen
    /// instances. It maintains a stack of screens, calls their Update and Draw
    /// methods at the appropriate times, and automatically routes input to the
    /// topmost active screen.
    /// </summary>
    public class ScreenManager : DrawableGameComponent
    {
        #region Fields

        List<GameScreen> screens = new List<GameScreen>();
        List<GameScreen> screensToUpdate = new List<GameScreen>();

        InputState input = new InputState();

        SpriteBatch spriteBatch;
        SpriteFont font;
        Texture2D blankTexture;

        bool isInitialized;

        bool traceEnabled;

        #endregion

        #region Properties


        /// <summary>
        /// A default SpriteBatch shared by all the screens. This saves
        /// each screen having to bother creating their own local instance.
        /// </summary>
        public SpriteBatch SpriteBatch
        {
            get { return spriteBatch; }
        }


        /// <summary>
        /// A default font shared by all the screens. This saves
        /// each screen having to bother loading their own local copy.
        /// </summary>
        public SpriteFont Font
        {
            get { return font; }
        }


        /// <summary>
        /// If true, the manager prints out a list of all the screens
        /// each time it is updated. This can be useful for making sure
        /// everything is being added and removed at the right times.
        /// </summary>
        public bool TraceEnabled
        {
            get { return traceEnabled; }
            set { traceEnabled = value; }
        }


        #endregion

        #region Initialization


        /// <summary>
        /// Constructs a new screen manager component.
        /// </summary>
        public ScreenManager(Game game)
            : base(game)
        {
        }


        /// <summary>
        /// Initializes the screen manager component.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            isInitialized = true;
        }


        /// <summary>
        /// Load your graphics content.
        /// </summary>
        protected override void LoadContent()
        {
            // Load content belonging to the screen manager.
            ContentManager content = Game.Content;

            spriteBatch = new SpriteBatch(GraphicsDevice);
            font = content.Load<SpriteFont>("menufont");
            blankTexture = content.Load<Texture2D>("blank");

            // Tell each of the screens to load their content.
            foreach (GameScreen screen in screens)
            {
                screen.LoadContent();
            }
        }


        /// <summary>
        /// Unload your graphics content.
        /// </summary>
        protected override void UnloadContent()
        {
            // Tell each of the screens to unload their content.
            foreach (GameScreen screen in screens)
            {
                screen.UnloadContent();
            }
        }


        #endregion

        #region Update and Draw


        /// <summary>
        /// Allows each screen to run logic.
        /// </summary>
        public override void Update(GameTime gameTime)
        {
            // Read the keyboard and gamepad.
            input.Update();

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

            foreach (GameScreen screen in screens)
                screensToUpdate.Add(screen);

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

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

                screensToUpdate.RemoveAt(screensToUpdate.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(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;
                }
            }

            // Print debug trace?
            if (traceEnabled)
                TraceScreens();
        }


        /// <summary>
        /// Prints a list of all the screens, for debugging.
        /// </summary>
        void TraceScreens()
        {
            List<string> screenNames = new List<string>();

            foreach (GameScreen screen in screens)
                screenNames.Add(screen.GetType().Name);

            Trace.WriteLine(string.Join(", ", screenNames.ToArray()));
        }


        /// <summary>
        /// Tells each screen to draw itself.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            foreach (GameScreen screen in screens)
            {
                if (screen.ScreenState == ScreenState.Hidden)
                    continue;

                screen.Draw(gameTime);
            }
        }


        #endregion

        #region Public Methods


        /// <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);
        }


        /// <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);
        }


        /// <summary>
        /// Expose an array holding all the screens. We return a copy rather
        /// than the real master list, because screens should only ever be added
        /// or removed using the AddScreen and RemoveScreen methods.
        /// </summary>
        public GameScreen[] GetScreens()
        {
            return screens.ToArray();
        }


        /// <summary>
        /// Helper draws a translucent black fullscreen sprite, used for fading
        /// screens in and out, and for darkening the background behind popups.
        /// </summary>
        public void FadeBackBufferToBlack(int alpha)
        {
            Viewport viewport = GraphicsDevice.Viewport;

            spriteBatch.Begin();

            spriteBatch.Draw(blankTexture,
                             new Rectangle(0, 0, viewport.Width, viewport.Height),
                             new Color(0, 0, 0, (byte)alpha));

            spriteBatch.End();
        }


        #endregion
    }
}

and here is GameplayScreen code:
#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.IO;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Media;
#endregion

namespace Platformer1
{
    /// <summary>
    /// This screen implements the actual game logic. It is just a
    /// placeholder to get the idea across: you'll probably want to
    /// put some more interesting gameplay in here!
    /// </summary>
    class GameplayScreen : GameScreen
    {
        #region Fields

        // Resources for drawing.

       
        private SpriteBatch spriteBatch;
        ScreenManager screenManager = new ScreenManager(game);

        // Global content.
        private SpriteFont hudFont;

        private Texture2D winOverlay;
        private Texture2D loseOverlay;
        private Texture2D diedOverlay;

        // Meta-level game state.
        private int levelIndex = -1;
        private Level level;
        private bool wasContinuePressed;

        // When the time remaining is less than the warning time, it blinks on the hud
        private static readonly TimeSpan WarningTime = TimeSpan.FromSeconds(30);

        ContentManager Content = new ContentManager(game);
     

        Vector2 playerPosition = new Vector2(100, 100);
        Vector2 enemyPosition = new Vector2(100, 100);

        Random random = new Random();

#if ZUNE
        private const int TargetFrameRate = 30;        
        private const int BackBufferWidth = 240;
        private const int BackBufferHeight = 320;
        private const Buttons ContinueButton = Buttons.B;        
#else
        private const int TargetFrameRate = 60;
        private const int BackBufferWidth = 1280;
        private const int BackBufferHeight = 720;
        private const Buttons ContinueButton = Buttons.A;
#endif

        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public GameplayScreen()
        {

            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }


        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        public override void LoadContent()
        {

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

            // Load fonts
            hudFont = Content.Load<SpriteFont>("Fonts/Hud");

            // Load overlay textures
            winOverlay = Content.Load<Texture2D>("Overlays/you_win");
            loseOverlay = Content.Load<Texture2D>("Overlays/you_lose");
            diedOverlay = Content.Load<Texture2D>("Overlays/you_died");



            MediaPlayer.IsRepeating = true;
            MediaPlayer.Play(Content.Load<Song>("Sounds/Music"));

            LoadNextLevel();
            // A real game would probably have more content than this sample, so
            // it would take longer to load. We simulate that by delaying for a
            // while, giving you a chance to admire the beautiful loading screen.
            Thread.Sleep(1000);

            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            ScreenManager.Game.ResetElapsedTime();
        }


        /// <summary>
        /// Unload graphics content used by the game.
        /// </summary>
        public override void UnloadContent()
        {
            Content.Unload();
        }


        #endregion

        #region Update and Draw


        /// <summary>
        /// Updates the state of the game. This method checks the GameScreen.IsActive
        /// property, so the game will stop updating when the pause menu is active,
        /// or if you tab away to a different application.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            HandleInput();

            level.Update(gameTime);

            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }

        private void HandleInput()
        {
            KeyboardState keyboardState = Keyboard.GetState();
            GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);

            // Exit the game when back is pressed.
            if (gamepadState.Buttons.Back == ButtonState.Pressed)
                screenManager.Game.Exit();

            bool continuePressed =
                keyboardState.IsKeyDown(Keys.Space) ||
                gamepadState.IsButtonDown(ContinueButton);

            // Perform the appropriate action to advance the game and
            // to get the player back to playing.
            if (!wasContinuePressed && continuePressed)
            {
                if (!level.Player.IsAlive)
                {
                    level.StartNewLife();
                }
                else if (level.TimeRemaining == TimeSpan.Zero)
                {
                    if (level.ReachedExit)
                        LoadNextLevel();
                    else
                        ReloadCurrentLevel();
                }
            }

            wasContinuePressed = continuePressed;
        }

        private void LoadNextLevel()
        {
            // Find the path of the next level.
            string levelPath;

            // Loop here so we can try again when we can't find a level.
            while (true)
            {
                // Try to find the next level. They are sequentially numbered txt files.
                levelPath = String.Format("Levels/{0}.txt", ++levelIndex);
                levelPath = Path.Combine(StorageContainer.TitleLocation, "Content/" + levelPath);
                if (File.Exists(levelPath))
                    break;

                // If there isn't even a level 0, something has gone wrong.
                if (levelIndex == 0)
                    throw new Exception("No levels found.");

                // Whenever we can't find a level, start over again at 0.
                levelIndex = -1;
            }

            // Unloads the content for the current level before loading the next one.
            if (level != null)
                level.Dispose();

            // Load the level.
            level = new Level(screenManager.Game.Services, levelPath);
        }

        private void ReloadCurrentLevel()
        {
            --levelIndex;
            LoadNextLevel();
        }


        /// <summary>
        /// Lets the game respond to player input. Unlike the Update method,
        /// this will only be called when the gameplay screen is active.
        /// </summary>
        public override void HandleInput(InputState input)
        {
          if (input == null)
                throw new ArgumentNullException("input");

            // Look up inputs for the active player profile.
            int playerIndex = (int)ControllingPlayer.Value;

            KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
            GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];

            // The game pauses either if the user presses the pause button, or if
            // they unplug the active gamepad. This requires us to keep track of
            // whether a gamepad was ever plugged in, because we don't want to pause
            // on PC if they are playing with a keyboard and have no gamepad at all!
            bool gamePadDisconnected = !gamePadState.IsConnected &&
                                       input.GamePadWasConnected[playerIndex];

            if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
            {
                ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
            }
            else
            {
                // Otherwise move the player position.
                Vector2 movement = Vector2.Zero;

                if (keyboardState.IsKeyDown(Keys.Left))
                    movement.X--;

                if (keyboardState.IsKeyDown(Keys.Right))
                    movement.X++;

                if (keyboardState.IsKeyDown(Keys.Up))
                    movement.Y--;

                if (keyboardState.IsKeyDown(Keys.Down))
                    movement.Y++;

                Vector2 thumbstick = gamePadState.ThumbSticks.Left;

                movement.X += thumbstick.X;
                movement.Y -= thumbstick.Y;

                if (movement.Length() > 1)
                    movement.Normalize();

                playerPosition += movement * 2;
        }
    }
       


        /// <summary>
        /// Draws the gameplay screen.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            // This game has a blue background. Why? Because!
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.CornflowerBlue, 0, 0);

            level.Draw(gameTime, spriteBatch);

            DrawHud();


            // If the game is transitioning on or off, fade it out to black.
            if (TransitionPosition > 0)
                ScreenManager.FadeBackBufferToBlack(255 - TransitionAlpha);

            base.Draw(gameTime);
        }

        private void DrawHud()
       {
            spriteBatch.Begin();
            Rectangle titleSafeArea = screenManager.GraphicsDevice.Viewport.TitleSafeArea;
            Vector2 hudLocation = new Vector2(titleSafeArea.X, titleSafeArea.Y);
            Vector2 center = new Vector2(titleSafeArea.X + titleSafeArea.Width / 2.0f,
                                         titleSafeArea.Y + titleSafeArea.Height / 2.0f);

            // Draw time remaining. Uses modulo division to cause blinking when the
            // player is running out of time.
            string timeString = "TIME: " + level.TimeRemaining.Minutes.ToString("00") + ":" + level.TimeRemaining.Seconds.ToString("00");
            Color timeColor;
            if (level.TimeRemaining > WarningTime ||
                level.ReachedExit ||
                (int)level.TimeRemaining.TotalSeconds % 2 == 0)
            {
                timeColor = Color.Yellow;
            }
            else
            {
                timeColor = Color.Red;
            }
            DrawShadowedString(hudFont, timeString, hudLocation, timeColor);

            // Draw score
            float timeHeight = hudFont.MeasureString(timeString).Y;
            DrawShadowedString(hudFont, "SCORE: " + level.Score.ToString(), hudLocation + new Vector2(0.0f, timeHeight * 1.2f), Color.Yellow);

            // Determine the status overlay message to show.
            Texture2D status = null;
            if (level.TimeRemaining == TimeSpan.Zero)
            {
                if (level.ReachedExit)
                {
                    status = winOverlay;
                }
                else
                {
                    status = loseOverlay;
                }
            }
            else if (!level.Player.IsAlive)
            {
                status = diedOverlay;
            }

            if (status != null)
            {
                // Draw status message.
                Vector2 statusSize = new Vector2(status.Width, status.Height);
                spriteBatch.Draw(status, center - statusSize / 2, Color.White);

              
            }
            spriteBatch.End();
        }

        private void DrawShadowedString(SpriteFont font, string value, Vector2 position, Color color)
        {
            spriteBatch.DrawString(font, value, position + new Vector2(1.0f, 1.0f), Color.Black);
            spriteBatch.DrawString(font, value, position, color);
        }



        #endregion
    }
}

thanks for any input.

Share this post


Link to post
Share on other sites
Deyja    920
You've pasted the code from the game state management sample.

This is not where your error is.

Paste the code where you actually get the error.

Share this post


Link to post
Share on other sites
xtheendx    127
Quote:
Original post by Deyja
You've pasted the code from the game state management sample.

This is not where your error is.

Paste the code where you actually get the error.




It says the error occurs in the GameplayScreen file. Specifically these two statements in the GamePlayScreen.



ScreenManager screenManager = new ScreenManager(game);


ContentManager Content = new ContentManager(game);


with the exact error message

Error 1 The name 'game' does not exist in the current context
Error 2 The name 'game' does not exist in the current context


Here is PlatformerGame class if that helps, as that contains main.


#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.IO;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Media;
#endregion


namespace Platformer1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class PlatformerGame : Microsoft.Xna.Framework.Game
{
// Resources for drawing.
private GraphicsDeviceManager graphics;

ScreenManager screenManager;




#if ZUNE
private const int TargetFrameRate = 30;
private const int BackBufferWidth = 240;
private const int BackBufferHeight = 320;
private const Buttons ContinueButton = Buttons.B;
#else
private const int TargetFrameRate = 60;
private const int BackBufferWidth = 1280;
private const int BackBufferHeight = 720;
private const Buttons ContinueButton = Buttons.A;
#endif

public PlatformerGame()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = BackBufferWidth;
graphics.PreferredBackBufferHeight = BackBufferHeight;

Content.RootDirectory = "Content";

// Create the screen manager component.
screenManager = new ScreenManager(this);

Components.Add(screenManager);

// Activate the first screens.
screenManager.AddScreen(new BackgroundScreen(), null);
screenManager.AddScreen(new MainMenuScreen(), null);

// Framerate differs between platforms.
TargetElapsedTime = TimeSpan.FromTicks(TimeSpan.TicksPerSecond / TargetFrameRate);
}


/// <summary>
/// Draws the game from background to foreground.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);

// The real drawing happens inside the screen manager component.
base.Draw(gameTime);
}


}
}



thanks and sorry for confusion.

Share this post


Link to post
Share on other sites
j0mich01    137
it looks like you are using the GameStateManagement Sample and if that is the case you don't need to create a ScreenManager in the GameplayScreen. There only needs to be one ScreenManager and it is created in game.cs. You then can access that global screenmanager from all screens including the gameplayscreen. About creating the ContentManager, it can be done like this:
content = new ContentManager(ScreenManager.Game.Services, "Content");

If you have any more questions or if this doesn't help just let me know.

Edit: From looking at your code a little more closely I can see what you are trying to do. It looks like you are trying combine the Platformer Game Sample with the GameStateManagement Sample (I had to do this for a class). I mentioned this earlier but I'm going to go into a little more detail. The ScreenManager basically manages all of the screens and handles transitions between them. It also supplies all screens with access to a SpriteBatch and the GraphicsDevice. I noticed you were creating a spritebatch in your LoadContent of your gameplayscreen, but you should probably just use the one that the ScreenManager supplies. You can do it like this.


spritebatch = ScreenManager.SpriteBatch;

Instead of this line:

spriteBatch = new SpriteBatch(screenManager.GraphicsDevice);

Combining these two samples together isn't incredibly difficult, but it does require a little insight at how the GameStateManagement Sample works.

Hope this helps.

[Edited by - j0mich01 on June 19, 2009 10:45:16 PM]

Share this post


Link to post
Share on other sites
xtheendx    127
Quote:
Original post by j0mich01
it looks like you are using the GameStateManagement Sample and if that is the case you don't need to create a ScreenManager in the GameplayScreen. There only needs to be one ScreenManager and it is created in game.cs. You then can access that global screenmanager from all screens including the gameplayscreen. About creating the ContentManager, it can be done like this:
content = new ContentManager(ScreenManager.Game.Services, "Content");

If you have any more questions or if this doesn't help just let me know.

Edit: From looking at your code a little more closely I can see what you are trying to do. It looks like you are trying combine the Platformer Game Sample with the GameStateManagement Sample (I had to do this for a class). I mentioned this earlier but I'm going to go into a little more detail. The ScreenManager basically manages all of the screens and handles transitions between them. It also supplies all screens with access to a SpriteBatch and the GraphicsDevice. I noticed you were creating a spritebatch in your LoadContent of your gameplayscreen, but you should probably just use the one that the ScreenManager supplies. You can do it like this.


spritebatch = ScreenManager.SpriteBatch;

Instead of this line:

spriteBatch = new SpriteBatch(screenManager.GraphicsDevice);

Combining these two samples together isn't incredibly difficult, but it does require a little insight at how the GameStateManagement Sample works.

Hope this helps.




Thanks for help, really glad you have don't this before, I have been trying to get this to work forever. I took your advise and edited my code to implenment your changes. I replaced my call to contentmanager with yours and took out call to screenmanager and just left it in PlatformerGame.cs and made change to spritebatch call in LoadContent.

That left with me with these errors...

Error 1 Invalid token '=' in class, struct, or interface member declaration C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 57 17 Platformer1
Error 2 Method must have a return type C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 57 23 Platformer1
Error 3 Identifier expected C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 57 65 Platformer1
Error 4 Type expected C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 57 67 Platformer1
Error 5 The name 'Content' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 103 23 Platformer1
Error 6 The name 'Content' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 106 26 Platformer1
Error 7 The name 'Content' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 107 27 Platformer1
Error 8 The name 'Content' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 108 27 Platformer1
Error 9 The name 'Content' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 113 30 Platformer1
Error 10 The name 'Content' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 133 13 Platformer1
Error 11 'Platformer1.GameScreen.screenManager' is inaccessible due to its protection level C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 163 17 Platformer1
Error 12 'Platformer1.GameScreen.screenManager' is inaccessible due to its protection level C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 216 31 Platformer1
Error 13 'Platformer1.GameScreen.screenManager' is inaccessible due to its protection level C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\Screens\GameplayScreen.cs 307 39 Platformer1
Error 14 The name 'screenManager' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\PlatformerGame.cs 46 13 Platformer1
Error 15 The name 'screenManager' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\PlatformerGame.cs 48 28 Platformer1
Error 16 The name 'screenManager' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\PlatformerGame.cs 51 13 Platformer1
Error 17 The name 'screenManager' does not exist in the current context C:\Users\Kaiju\Documents\Visual Studio 2008\Projects\Platformer1\Platformer1\PlatformerGame.cs 52 13 Platformer1




here are the gameplayscreen and platformergame files..since those are the ones that received changes.


#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.IO;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Media;
#endregion

namespace Platformer1
{
/// <summary>
/// This screen implements the actual game logic. It is just a
/// placeholder to get the idea across: you'll probably want to
/// put some more interesting gameplay in here!
/// </summary>
class GameplayScreen : GameScreen
{
#region Fields

// Resources for drawing.



private SpriteBatch spriteBatch;


// Global content.
private SpriteFont hudFont;

private Texture2D winOverlay;
private Texture2D loseOverlay;
private Texture2D diedOverlay;

// Meta-level game state.
private int levelIndex = -1;
private Level level;
private bool wasContinuePressed;

// When the time remaining is less than the warning time, it blinks on the hud
private static readonly TimeSpan WarningTime = TimeSpan.FromSeconds(30);

Content = new ContentManager(ScreenManager.Game.Services, "Content");


Vector2 playerPosition = new Vector2(100, 100);
Vector2 enemyPosition = new Vector2(100, 100);

Random random = new Random();

#if ZUNE
private const int TargetFrameRate = 30;
private const int BackBufferWidth = 240;
private const int BackBufferHeight = 320;
private const Buttons ContinueButton = Buttons.B;
#else
private const int TargetFrameRate = 60;
private const int BackBufferWidth = 1280;
private const int BackBufferHeight = 720;
private const Buttons ContinueButton = Buttons.A;
#endif

#endregion

#region Initialization


/// <summary>
/// Constructor.
/// </summary>
public GameplayScreen()
{

TransitionOnTime = TimeSpan.FromSeconds(1.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
}


/// <summary>
/// Load graphics content for the game.
/// </summary>
public override void LoadContent()
{


// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = ScreenManager.SpriteBatch;
// Load fonts
hudFont = Content.Load<SpriteFont>("Fonts/Hud");

// Load overlay textures
winOverlay = Content.Load<Texture2D>("Overlays/you_win");
loseOverlay = Content.Load<Texture2D>("Overlays/you_lose");
diedOverlay = Content.Load<Texture2D>("Overlays/you_died");



MediaPlayer.IsRepeating = true;
MediaPlayer.Play(Content.Load<Song>("Sounds/Music"));

LoadNextLevel();
// A real game would probably have more content than this sample, so
// it would take longer to load. We simulate that by delaying for a
// while, giving you a chance to admire the beautiful loading screen.
Thread.Sleep(1000);

// once the load has finished, we use ResetElapsedTime to tell the game's
// timing mechanism that we have just finished a very long frame, and that
// it should not try to catch up.
ScreenManager.Game.ResetElapsedTime();
}


/// <summary>
/// Unload graphics content used by the game.
/// </summary>
public override void UnloadContent()
{
Content.Unload();
}


#endregion

#region Update and Draw


/// <summary>
/// Updates the state of the game. This method checks the GameScreen.IsActive
/// property, so the game will stop updating when the pause menu is active,
/// or if you tab away to a different application.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
HandleInput();

level.Update(gameTime);

base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
}

private void HandleInput()
{
KeyboardState keyboardState = Keyboard.GetState();
GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);

// Exit the game when back is pressed.
if (gamepadState.Buttons.Back == ButtonState.Pressed)
screenManager.Game.Exit();

bool continuePressed =
keyboardState.IsKeyDown(Keys.Space) ||
gamepadState.IsButtonDown(ContinueButton);

// Perform the appropriate action to advance the game and
// to get the player back to playing.
if (!wasContinuePressed && continuePressed)
{
if (!level.Player.IsAlive)
{
level.StartNewLife();
}
else if (level.TimeRemaining == TimeSpan.Zero)
{
if (level.ReachedExit)
LoadNextLevel();
else
ReloadCurrentLevel();
}
}

wasContinuePressed = continuePressed;
}

private void LoadNextLevel()
{
// Find the path of the next level.
string levelPath;

// Loop here so we can try again when we can't find a level.
while (true)
{
// Try to find the next level. They are sequentially numbered txt files.
levelPath = String.Format("Levels/{0}.txt", ++levelIndex);
levelPath = Path.Combine(StorageContainer.TitleLocation, "Content/" + levelPath);
if (File.Exists(levelPath))
break;

// If there isn't even a level 0, something has gone wrong.
if (levelIndex == 0)
throw new Exception("No levels found.");

// Whenever we can't find a level, start over again at 0.
levelIndex = -1;
}

// Unloads the content for the current level before loading the next one.
if (level != null)
level.Dispose();

// Load the level.
level = new Level(screenManager.Game.Services, levelPath);
}

private void ReloadCurrentLevel()
{
--levelIndex;
LoadNextLevel();
}


/// <summary>
/// Lets the game respond to player input. Unlike the Update method,
/// this will only be called when the gameplay screen is active.
/// </summary>
public override void HandleInput(InputState input)
{
if (input == null)
throw new ArgumentNullException("input");

// Look up inputs for the active player profile.
int playerIndex = (int)ControllingPlayer.Value;

KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];

// The game pauses either if the user presses the pause button, or if
// they unplug the active gamepad. This requires us to keep track of
// whether a gamepad was ever plugged in, because we don't want to pause
// on PC if they are playing with a keyboard and have no gamepad at all!
bool gamePadDisconnected = !gamePadState.IsConnected &&
input.GamePadWasConnected[playerIndex];

if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
{
ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
}
else
{
// Otherwise move the player position.
Vector2 movement = Vector2.Zero;

if (keyboardState.IsKeyDown(Keys.Left))
movement.X--;

if (keyboardState.IsKeyDown(Keys.Right))
movement.X++;

if (keyboardState.IsKeyDown(Keys.Up))
movement.Y--;

if (keyboardState.IsKeyDown(Keys.Down))
movement.Y++;

Vector2 thumbstick = gamePadState.ThumbSticks.Left;

movement.X += thumbstick.X;
movement.Y -= thumbstick.Y;

if (movement.Length() > 1)
movement.Normalize();

playerPosition += movement * 2;
}
}



/// <summary>
/// Draws the gameplay screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
// This game has a blue background. Why? Because!
ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
Color.CornflowerBlue, 0, 0);

level.Draw(gameTime, spriteBatch);

DrawHud();


// If the game is transitioning on or off, fade it out to black.
if (TransitionPosition > 0)
ScreenManager.FadeBackBufferToBlack(255 - TransitionAlpha);

base.Draw(gameTime);
}

private void DrawHud()
{
spriteBatch.Begin();
Rectangle titleSafeArea = screenManager.GraphicsDevice.Viewport.TitleSafeArea;
Vector2 hudLocation = new Vector2(titleSafeArea.X, titleSafeArea.Y);
Vector2 center = new Vector2(titleSafeArea.X + titleSafeArea.Width / 2.0f,
titleSafeArea.Y + titleSafeArea.Height / 2.0f);

// Draw time remaining. Uses modulo division to cause blinking when the
// player is running out of time.
string timeString = "TIME: " + level.TimeRemaining.Minutes.ToString("00") + ":" + level.TimeRemaining.Seconds.ToString("00");
Color timeColor;
if (level.TimeRemaining > WarningTime ||
level.ReachedExit ||
(int)level.TimeRemaining.TotalSeconds % 2 == 0)
{
timeColor = Color.Yellow;
}
else
{
timeColor = Color.Red;
}
DrawShadowedString(hudFont, timeString, hudLocation, timeColor);

// Draw score
float timeHeight = hudFont.MeasureString(timeString).Y;
DrawShadowedString(hudFont, "SCORE: " + level.Score.ToString(), hudLocation + new Vector2(0.0f, timeHeight * 1.2f), Color.Yellow);

// Determine the status overlay message to show.
Texture2D status = null;
if (level.TimeRemaining == TimeSpan.Zero)
{
if (level.ReachedExit)
{
status = winOverlay;
}
else
{
status = loseOverlay;
}
}
else if (!level.Player.IsAlive)
{
status = diedOverlay;
}

if (status != null)
{
// Draw status message.
Vector2 statusSize = new Vector2(status.Width, status.Height);
spriteBatch.Draw(status, center - statusSize / 2, Color.White);


}
spriteBatch.End();
}

private void DrawShadowedString(SpriteFont font, string value, Vector2 position, Color color)
{
spriteBatch.DrawString(font, value, position + new Vector2(1.0f, 1.0f), Color.Black);
spriteBatch.DrawString(font, value, position, color);
}



#endregion
}
}






#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.IO;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Media;
#endregion


namespace Platformer1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class PlatformerGame : Microsoft.Xna.Framework.Game
{
// Resources for drawing.
private GraphicsDeviceManager graphics;


#if ZUNE
private const int TargetFrameRate = 30;
private const int BackBufferWidth = 240;
private const int BackBufferHeight = 320;
private const Buttons ContinueButton = Buttons.B;
#else
private const int TargetFrameRate = 60;
private const int BackBufferWidth = 1280;
private const int BackBufferHeight = 720;
private const Buttons ContinueButton = Buttons.A;
#endif

public PlatformerGame()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = BackBufferWidth;
graphics.PreferredBackBufferHeight = BackBufferHeight;

Content.RootDirectory = "Content";

// Create the screen manager component.
screenManager = new ScreenManager(this);

Components.Add(screenManager);

// Activate the first screens.
screenManager.AddScreen(new BackgroundScreen(), null);
screenManager.AddScreen(new MainMenuScreen(), null);

// Framerate differs between platforms.
TargetElapsedTime = TimeSpan.FromTicks(TimeSpan.TicksPerSecond / TargetFrameRate);
}


/// <summary>
/// Draws the game from background to foreground.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);

// The real drawing happens inside the screen manager component.
base.Draw(gameTime);
}


}
}





When you combined these two, did you do it about that same as I am trying to do it. Seems like there is a big chunk i am missing for it to be this messed up...but i cant figure it out. I basically took all code from PlatformerGame and put it in GameplayScreen....thought it was going to be simple....has turned into a huge headache though. I really appreciate any help you can provide.

thanks

Share this post


Link to post
Share on other sites
j0mich01    137
Sorry I didn't post earlier. I don't really know exactly what is causing your problems, but my advice to you would be to study how both the GamestateManagement sample and the platformer game work before you try to combine them. It wasn't that difficult to do, but that was mainly a result of me knowing what the original two projects did and how they worked.

Also from looking at you code you might want to study up on c# as well. I noticed that at least some of the errors are related to this line in the gameplayscreen

Content = new ContentManager(ScreenManager.Game.Services, "Content");

You need to change this to just:
ContentManager Content;

and then in the LoadContent() function actually create the ContentManager instance.

Content = new ContentManager(ScreenManager.Game.Services, "Content");

Share this post


Link to post
Share on other sites
xtheendx    127
Quote:
Original post by j0mich01
Sorry I didn't post earlier. I don't really know exactly what is causing your problems, but my advice to you would be to study how both the GamestateManagement sample and the platformer game work before you try to combine them. It wasn't that difficult to do, but that was mainly a result of me knowing what the original two projects did and how they worked.

Also from looking at you code you might want to study up on c# as well. I noticed that at least some of the errors are related to this line in the gameplayscreen

Content = new ContentManager(ScreenManager.Game.Services, "Content");

You need to change this to just:
ContentManager Content;

and then in the LoadContent() function actually create the ContentManager instance.

Content = new ContentManager(ScreenManager.Game.Services, "Content");




thanks man your response got me thinking and with your advice i was able to get things going better...still some work to do but was able to figure out some stuff about c# to get rid of my errors and learn more about how things were working. thanks man

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this