Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7590055
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T20:18:43+00:00 2026-05-30T20:18:43+00:00

I am learning some C# by improving an open source C# text-based adventure. I

  • 0

I am learning some C# by improving an open source C# text-based adventure. I am working on saving all the player data to a file and loading it.

When I try to serialize my player class, the compiler throws the error:

'Project1.Player' is a 'type' but is used like a 'variable' Program.cs:72

UPDATED
Ok to make things easier, I updated all my code to its current state.
The new error I am getting every time I reference player is:
The name 'player' does not exist in the current context

Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Project1
{
    class Program
    {
        public static int windowWidth = 80;
        public static int windowHeight = 35;
        public static bool run = true;
        public static string errorMessage;
        public static bool isError = false;

        static void Main(string[] args)
        {
            // setup console window
            Console.Clear(); 
            // set size
            Console.SetWindowSize(windowWidth, windowHeight);
            // remove scroll bar with buffer size equal to window size
            Console.BufferWidth = windowWidth;
            Console.BufferHeight = windowHeight;

            // generate world
            Player player = new Player();
            World.GenerateWorld();

            // begin character creation
            string name = Text.Prompt("Welcome stranger.  What is your name?");
            player.name = name;
            player.inventory.Add(new Item("Candle", "A single white candle.", 22));

            Text.WriteLine("Thanks, " + name);
            Text.WriteLine("Press any key to get started.");
            Console.ReadKey();
            Console.Clear();
            Text.WriteLine("The last thing you remember is battling the Ancient LichLord deep within a cavern beneath Death Mountain.   Now suddenly, you are surrounded by the darkness of true night as you stand in front of an ancient stone castle of complex architecture.  Looking up, you notice the faint glow of a light coming from an old clock tower, high above the castle.  The doors to the castle are large and covered in an ancient mold. Unsure of what to do, you drag open the large wooden door, light the candle you found in your pocket, and step into the castle. \n \nPress a key...");
            Console.ReadKey();
            Console.Clear();

            while (run)
            {
                if (!isError)
                {
                    Text.SetPrompt();
                    World.LocationDescription();

                    string temp = Text.Prompt("");
                    Console.Clear();
                    player.Do(temp);
                }
                // there is an error
                else
                {
                    DisplayError();
                }
            }
        }

        // stream writer to write to file.
        public static void SaveGame()
        {
            try
            {
                using (Stream stream = File.Open("save.dat", FileMode.Create))
                {
                    BinaryFormatter bin = new BinaryFormatter();
                    bin.Serialize(stream, player);
                }
            }
            catch (IOException)
            {
            }
        }

        public static void LoadGame()
        {
            if (File.Exists("save.dat"))
            {
                try
                {
                using (Stream stream = File.Open("save.dat", FileMode.Open))
                    {
                        BinaryFormatter bin = new BinaryFormatter();
                        var player = bin.Deserialize(stream);
                    }
                }
                catch (IOException)
                {
                }
            }
            else
            {
                Program.SetError("The savegame does not exist!");
            }
        }
        // stream reader to find file
        //public static void LoadGame()
        //{
        //    try
        //    {
        //        using (Stream stream = File.Open("data.bin", FileMode.Open))
        //        {
        //            BinaryFormatter bin = new BinaryFormatter();
        //            World.map = (List<Location>)bin.Deserialize(stream);
        //        }
        //    }
        //    catch (IOException)
        //    {
        //    }
        //}

        public static void WinGame()
        {
            run = false;
            Text.WriteLine("As you place the crown upon your head, your vision begins to blur and you fall to the floor.   You wake up in a hot cavern, lit by a few torches on the wall.  This is the cavern of the Ancient LichLord, and you have escaped his twisted maze. ");
        }

        #region Error Handling
        public static void SetError(string aText)
        {
            isError = true;
            errorMessage = aText;
        }

        public static void UnsetError()
        {
            isError = false;
            errorMessage = "";
        }

        public static void DisplayError()
        {
            Text.WriteColor("|r|" + errorMessage + "|g|");
            Text.BlankLines(2);
            UnsetError();
        }
        #endregion
    }
}

Player.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Project1
{
    [Serializable()]
    class Player
    {
        public string name;
        //public static string desc;
        //public static int[] stats;
        public int location;
        public List<Item> inventory = new List<Item>();
        public string[] possibleActions = new string[] { "move", "m", "look", "l", "take", "t", "drop", "d", "use", "u", "inventory", "i", "help", "h", "quit", "exit", "save", "load", "name" };

        /// <summary>
        /// Player action, array of predicate and target
        /// </summary>
        /// <param name="aAction"></param>
        /// <returns></returns>
        public void Do(string aText)
        {
            string verb = "";
            string noun = "";

            // check if there is a space in the given command
            if (aText.IndexOf(' ') != -1)
            {
                // split the string into the verb and noun
                string[] temp = aText.Split(new char[] { ' ' }, 2);
                verb = temp[0].ToLower();
                noun = temp[1].ToLower();
            }
            else
            {
                // verb only
                verb = aText.ToLower();
            }

            if (IsAction(verb))
            {
                // do whatever action
                switch (verb)
                {
                    case "move":
                    case "m":
                        if (noun == "")
                            Program.SetError("You must specify a location to move.");
                        else
                            MoveTo(noun);
                        break;

                    case "look":
                    case "l":
                        if (noun == "")
                            noun = World.map[player.location].name;

                        LookAt(noun);
                        break;

                    case "take":
                    case "t":
                        if (noun == "")
                            Program.SetError("You must specify an item to take.");
                        else
                            PickUpItem(noun);
                        break;

                    case "drop":
                    case "d":
                        if (noun == "")
                            Program.SetError("You must specify an item to drop.");
                        else
                            DropItem(noun);
                        break;

                    case "use":
                    case "u":
                        if (noun == "")
                            Program.SetError("You must specify an item to use.");
                        else
                            UseItem(noun);
                        break;

                    case "inventory":
                    case "i":
                        ListInventory();
                        break;

                    case "help":
                    case "h":
                        ListActions();
                        break;

                    case "quit":
                    case "exit":
                        QuitPrompt();
                        break;

                    case "save":
                        Program.SaveGame();
                        break;

                    case "load":
                        Program.LoadGame();
                        break;
                    case "name":
                        Console.WriteLine("Your name is {0}", player.name);
                        Console.WriteLine("");
                        break;
                }
            }
            else
            {
                // not a real action
                Program.SetError("Action not found.");
            }
        }

        public void MoveTo(string location)
        {
            // is location?
            if (World.IsLocation(location))
            {
                int locationId = World.GetLocationIdByName(location);

                if (World.IsLocationExit(location))
                {
                    // set the player's new location
                    player.location = locationId;
                }
                else
                {
                    Program.SetError("You can't get there from here.");
                }
            }
            else
            {
                Program.SetError("That is not a real location.");
            }
        }

        public void LookAt(string noun)
        {
            // is location?  
            if (World.IsLocation(noun))
            {
                Console.Clear();
                World.ShowHiddenItems();
                Text.BlankLines(2);
            }
            // is item?
            else if (Item.IsItemInInventory(noun) || Item.IsItemInLocation(noun))
            {
                Console.Clear();
                Text.WriteLine(Item.GetItemDescByName(noun));
                Text.BlankLines(2);
            }
        }

        public void PickUpItem(string item)
        {
            // is item?
            if (Item.IsItemInLocation(item))
            {
                // get description
                string desc = Item.GetItemDescByName(item);
                int actionLocationId = Item.GetItemActionLocationIdByName(item);
                // remove item from location
                Item.RemoveItemFromLocation(item);
                // add item to inventory
                player.inventory.Add(new Item(item, desc, actionLocationId));
            }
            else
            {
                Program.SetError("Item not found in this location.");
            }
        }

        public void DropItem(string item)
        {
            //is item?
            if (Item.IsItemInInventory(item))
            {
                string desc = Item.GetItemDescByName(item);
                int actionLocationId = Item.GetItemActionLocationIdByName(item);

                // remove item from inventory
                RemoveInventoryItem(item);

                // add item to location
                World.map[player.location].items.Add(new Item(item, desc, actionLocationId));
            }
            else
            {
                Program.SetError("Item not in inventory.");
            }
        }

        public void RemoveInventoryItem(string item)
        {
            for (int i = 0; i < player.inventory.Count; i++)
            {
                if (player.inventory[i].name.ToLower() == item.ToLower())
                {
                    player.inventory.RemoveAt(i);
                }
            }
        }

        public void UseItem(string item)
        {
            // is item?
            if (Item.IsItemInInventory(item))
            {
                // get item actionLocationId
                int itemActionLocationId = Item.GetItemActionLocationIdByName(item);
                if (itemActionLocationId == player.location)
                {
                    World.UseItemInLocation(item);
                }
                else
                {
                    Program.SetError("You're not sure how that helps here.");
                }
            }
            else
            {
                Program.SetError("Item not in inventory");
            }
        }

        public void ListInventory()
        {
            Text.WriteLine("\n-- Inventory -- \n");

            for (int i = 0; i < player.inventory.Count; i++)
            {
                Text.WriteLine(i.ToString() + ": "+ player.inventory[i].name);
            }

            Text.BlankLines(2);
        }

        public void ListActions()
        {
            Text.BlankLines(2);

            //"move", "look", "take", "drop", "use", "inventory", "help"
            Text.WriteLine("\n-- Actions -- \n");
            Text.WriteLine("move - travel to another location.   usage: move entrance hall (or) m entrance hall");
            Text.WriteLine("look - look at a location or an item.   usage: look entrance hall (or) look sword (or) l entrance hall (or) l sword");
            Text.WriteLine("take - pick up an item in a location.   usage: take sword (or) t sword");
            Text.WriteLine("drop - drop an item from your inventory.   usage: drop sword (or) d sword");
            Text.WriteLine("use - use an item in your inventory.   usage: use key (or) u key");
            Text.WriteLine("inventory - show items in your inventory.   usage: inventory (or) i");
            Text.WriteLine("help - show this screen.   usage: help (or) h");
            Text.WriteLine("exit - quit the game.    usage: quit (or) exit");

            Text.BlankLines(2);
        }

        /// <summary>
        /// Check the legitmacy of the action
        /// </summary>
        /// <param name="aText"></param>
        /// <returns></returns>
        public bool IsAction(string aText)
        {
            for (int i = 0; i < possibleActions.Length; i++)
            {
                if (aText == possibleActions[i])
                {
                    return true;
                }
            }
            return false;
        }

        public void QuitPrompt()
        {
            Text.WriteLine("Are you sure you want to leave?  y/n");
            string answer = Console.ReadLine().ToLower();

            if (answer == "y" || answer == "yes")
            {
                Program.run = false;
            }
        }
    }
}

Item.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Project1
{
    class Item : Entity
    {
        public bool isHidden = false;
        public int actionLocationId;
        public string actionName;

        public Item(string aName, string aDesc, int aActionLocationId, bool aIsHidden = false, string aActionName = "use")
            :base(aName, aDesc)
        {
            actionLocationId = aActionLocationId;
            actionName = aActionName;

            if (aIsHidden)
                isHidden = aIsHidden;
        }

        /// <summary>
        /// Looks for item in player.inventory
        /// </summary>
        /// <param name="aName">name of the Item</param>
        /// <returns></returns>
        public static bool IsItemInInventory(string aName)
        {
            // look for item in inventory
            for (int i = 0; i < player.inventory.Count; i++)
            {
                if (player.inventory[i].name.ToLower() == aName.ToLower())
                {
                    return true;
                }
            }

            // not found
            return false;
        }

        /// <summary>
        /// Looks for item in current location
        /// </summary>
        /// <param name="aName">name of the Item</param>
        /// <returns></returns>
        public static bool IsItemInLocation(string aName)
        {
            // look for item in location
            for (int i = 0; i < World.map[player.location].items.Count; i++)
            {
                if (World.map[player.location].items[i].name.ToLower() == aName.ToLower())
                {
                    return true;
                }
            }

            // not found
            return false;
        }


        /// <summary>
        /// Items are only items if in player.inventory or player.location
        /// </summary>
        /// <param name="aName">name of the Item</param>
        /// <returns></returns>
        public static string GetItemDescByName(string aName)
        {
            // look for item in location
            for (int i = 0; i < World.map[player.location].items.Count; i++)
            {
                if (World.map[player.location].items[i].name.ToLower() == aName.ToLower())
                {
                    return World.map[player.location].items[i].description;
                }
            }

            // look for item in inventory
            for (int i = 0; i < player.inventory.Count; i++)
            {
                if (player.inventory[i].name.ToLower() == aName.ToLower())
                {
                    return player.inventory[i].description;
                }
            }

            // not found
            return "Item not found";
        }

        public static int GetItemActionLocationIdByName(string aName)
        {
            // look for item in inventory
            for (int i = 0; i < player.inventory.Count; i++)
            {
                if (player.inventory[i].name.ToLower() == aName.ToLower())
                {
                    return player.inventory[i].actionLocationId;
                }
            }

            // look for item in location
            for (int i = 0; i < World.map[player.location].items.Count; i++)
            {
                if (World.map[player.location].items[i].name.ToLower() == aName.ToLower())
                {
                    return World.map[player.location].items[i].actionLocationId;
                }
            }
            return -1;
        }

        public static void RemoveItemFromLocation(string item)
        {
            for (int i = 0; i < World.map[player.location].items.Count; i++ )
            {
                if (World.map[player.location].items[i].name.ToLower() == item.ToLower())
                {
                    World.map[player.location].items.RemoveAt(i);
                }
            }
        }
    }
}

Please note 3 things:

  1. I am learning C#, and I am coming from a JS background.
  2. I realize there are some things seriously wrong with how I am trying to save the player data, but that is why I’m here.
  3. This is the first time I’ve tried saving a large amount of data in a program, so there is a lot of experimentation going on here.
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T20:18:45+00:00Added an answer on May 30, 2026 at 8:18 pm

    You need to instantiate a Player object before you can use it, so this:

    Player.name = name;
    Player.inventory.Add(new Item("Candle", "A single white candle.", 22));
    

    Should be something like:

    var player = new Player();
    player.name = name;
    player.inventory.Add(new Item("Candle", "A single white candle.", 22));
    // etc...
    

    Just replace all of your Player. calls with player. (or whatever you decide to call your player variable) after you instantiate a Player object (using the new keyword).

    UPDATE

    Your Player class is effectively static (meaning there can only be one defined at a time). I’d recommend changing it to something more like:

    class Player
    {
        public string name;
        public int location;
        public List<Item> inventory = new List<Item>();
        public string[] possibleActions = new string[] { "move", "m", "look", "l", "take", "t", "drop", "d", "use", "u", "inventory", "i", "help", "h", "quit", "exit", "save", "load", "name" };
    
        /// <summary>
        /// Player action, array of predicate and target
        /// </summary>
        /// <param name="aAction"></param>
        /// <returns></returns>
        public void Do(string aText)
        {
            // ...
        }
    
        public void MoveTo(string location)
        {
            // ...
        }
    
        public void LookAt(string noun)
        {
            // ...
        }
    
        public void PickUpItem(string item)
        {
            // ...
        }
    
        public void DropItem(string item)
        {
            // ...
        }
    
        public void RemoveInventoryItem(string item)
        {
            // ...
        }
    
        public void UseItem(string item)
        {
            // ...
        }
    
        public void ListInventory()
        {
            // ...
        }
    
        public void ListActions()
        {
            // ...
        }
    
        /// <summary>
        /// Check the legitmacy of the action
        /// </summary>
        /// <param name="aText"></param>
        /// <returns></returns>
        public bool IsAction(string aText)
        {
            // ...
        }
    
        public void QuitPrompt()
        {
            // ...
        }
    }
    

    Then if you really only need one global instance of Player then define it as static in Program:

    public static Player CurrentPlayer = new Player();
    

    If you did it this way then you could access the Player instance like:

    CurrentPlayer.name = name;
    CurrentPlayer.inventory.Add(new Item("Candle", "A single white candle.", 22));
    

    On the other hand, if it isn’t important that you’re only working with a single instance of Player then you could just remove all of the static keywords from your Player class. That should allow you to get past your error.

    UPDATE

    My recommended solution from my comment below would look something roughly like (without all of the detail from the code in your question):

    public class Player
    {
        public static Player CurrentPlayer = new Player(); // This is your global instance
        public string name;
        // All of your other content here
    }
    
    public class Program
    {
        public static void Main()
        {
            // In here we can access our global instance of `Player` to change it as needed
            Player.CurrentPlayer.name = "Some Name Here";
        }
    }
    

    After adding the static CurrentPlayer field to the Player class, you can change all of your references to player in all three of your code files to Player.CurrentPlayer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been learning some Clojure, and I currently have a single .clj file which
I'm working on learning some Haskell (please excuse the newbie error)- This routine errors
I am currently working on learning some different aspects of WINAPI, including features introduced
Good evening everyone! I am working on learning some java and I have made
I'm interested in learning some (ideally) database agnostic ways of selecting the n th
Looking at learning some C since i saw in another SO question that is
I'm learning some OpenGL game programing, and I'm stuck in how to implement so
I am learning some COM code and the following code puzzled me. STDMETHODIMP _(ULONG)
I'm a beginner learning some assembly, when preserving the ESP register before a function
I'm interested in learning some python, and thought Pylons would be a good starting

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.