C# Workshop - Week 1 (Ch. 1 & 2) - Advanced

Started by
337 comments, last by paulecoyote 17 years, 1 month ago
i have a hard time understanding the difference between Starting an array like this:

Array names = Array.CreateInstance( typeof(String), 2, 4, 4 );

and like this:
string[,] names = new string[4, 4];i want to use it to insert items in the array:    class MapEngine    {        private byte xMaxArray = 40;        private byte yMaxArray = 40;        public byte ModxMaxArray        {            get { return xMaxArray; }            set { xMaxArray = value; }        }        public byte ModyMaxArray        {            get { return yMaxArray; }            set { yMaxArray = value; }        }        public void Map()         {            string[,] MapArray = new string[xMaxArray, yMaxArray];        }        public void InsterItem(string Item, byte X, byte Y)        {            MapArray.SetValue(Item, Y, X);        }        public string ReadItem(byte X, byte Y)        {            MapArray.GetValue(X, Y);        }    }        static void Main(string[] args)        {            MapEngine Map1 = new MapEngine();            Map1.Map();


But do i access the new maparray referring to it as map1 or MapArray?

[Edited by - alvarofrank on July 11, 2007 3:52:06 PM]
Advertisement
Quote: Original post by alvarofrank
i have a hard time understanding the difference between Starting an array like this:

Array names = Array.CreateInstance( typeof(String), 2, 4, 4 );

and like this:

string[,] names = new string[4, 4];

i want to use it to insert items in the array:

class MapEngine
{
private byte xMaxArray = 40;
private byte yMaxArray = 40;

public byte ModxMaxArray
{
get { return xMaxArray; }
set { xMaxArray = value; }
}

public byte ModyMaxArray
{
get { return yMaxArray; }
set { yMaxArray = value; }
}

public void Map()
{
string[,] MapArray = new string[xMaxArray, yMaxArray];
}

public void InsterItem(string Item, byte X, byte Y)
{
MapArray.SetValue(Item, Y, X);
}
public string ReadItem(byte X, byte Y)
{
MapArray.GetValue(X, Y);
}

}

static void Main(string[] args)
{
MapEngine Map1 = new MapEngine();
Map1.Map();

But do i access the new maparray referring to it as map1 or MapArray?


First of all, use the [ source lang="C#" ] and [ /source ] tags to display your source code, so that it gets a nice scrollbox, syntax highlighting, and correct formatting. Now, on to the question.

As you may have noticed, you cannot access your MapArray variable because it is a local variable, and gets thrown away once you leave the Map() function. InsertItem and ReadItem won't be able to find the variable because it won't exist after the Map() function is done running.

To access the elements of an array, you use the index operator, like this:
string[] array1;int[,] array2;string firstElement = array1[0];int firstInt = array2[0];array1[5] = "Hello";array2[3] = 54;
Mike Popoloski | Journal | SlimDX
Quote: Original post by JWalsh
Several people have pointed out how difficult it is to sort through 300+ posts in a single thread to determine if a question you asked has been answered, or worse, if your question has already been asked by someone else and THEN answered. To remedy this problem Superpig is currently researching a way to give the Workshop its own area here on GDNet, allowing for sub-forums, etc...This would enable us to have multiple threads per week, within a sub-forum designated for that week.


A QA forum for the workshop would do, or just keeping the lessons stickied and using this one. People could then post questions like this maybe:

[Week 1] What's the difference between a ref parameter and normal parameters?

And then if a thread has answers, one could assume that the query has been answered. Plus I guess it would make it easy to search for questions already asked.

I suppose that would quickly balloon though.
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.
When this workshop first started, I assumed that having this nice C# Workshop forum at the top of the list would let people post different topics depending on the questions they were having, and then others could answer them, or see if their question was already posted somewhere else. Why isn't posting allowed in this forum?
Mike Popoloski | Journal | SlimDX
JWalsh posted a example of expressions using components of RPGs. I wanted to see if I could expand on that. Despite programming in C++ on and off for seven years, this is the first time I've ever done anything related to "game programming." It's a very very very (I can't stress "very" enough) basic battle system. It actually could have ended up nicer. I wanted to use events to handle when a player was K.Oed. But it was 2:00 a.m in the morning, and I wanted it finished "now," so I took the easy way out. Just sharing it with ya'll:

using System;// A simple class to hold data for a hero or enemypublic class Character{    // Sets various attributes    public Character(int level, int hp, int strength, int armor)    {        this.level = level;        this.hp = hp;        this.strength = strength;        this.armor = armor;        this.koed = false;    }    public Character(): this(5, 40, 8, 7){}    public void SetStance(int val) { this.stance = val; }    public void Attack(Character enemy)    {        int modifier;        switch (this.stance)        {            case 1:                {                    this.armor += 3;                    this.strength -= 3;                } break;            case 2:                {                    this.armor -= 3;                    this.strength += 3;                } break;            default:                {                } break;        }        int damage = (this.level + this.strength) - enemy.Armor;        if (damage <= 0)            damage = 1;        enemy.Hp -= damage;        if(enemy.Hp <= 0)            enemy.KOED = true;        switch (this.stance)        {            case 1:                {                    this.armor -= 3;                    this.strength += 3;                    SetStance(0);                } break;            case 2:                {                    this.armor += 3;                    this.strength -= 3;                    SetStance(0);                } break;            default: { } break;        }    }    public int Level    {        get        {            return level;        }        set        {            level = value;        }    }    public int Hp    {        get        {            return hp;        }        set        {            hp = value;        }    }    public int Armor    {        get        {            return armor;        }        set        {            armor = value;        }    }    public int Strength    {        get        {            return strength;        }        set        {            strength = value;        }    }    public bool KOED    {        get        {            return koed;        }        set        {            koed = value;        }    }    public int Stance    {        get        {            return stance;        }    }    protected int level;            // The level of the entity    protected int hp;               // The current hitpoints of the character    protected int strength;         // The character's attack rating    protected int armor;            // The defense of the character    protected bool koed;            // If the character has 0 or less hp, this should be true    protected int stance;           // The stance of the character. 1 = defensive stance                                    // 2 = berserk stance}class Game{    public void ProcessAI(Character ai, Character enemy, Random rand)    {        if ((rand.Next() % 2) == 1)             // We attack the hero        {            ai.Attack(enemy);        }        else                             // We set our stance        {            if (ai.Stance != 0)            {                Console.WriteLine("Stance has already been set. Turn forfeited.");            }            else            {                ai.SetStance(rand.Next(1, 2));            }        }    }    public void ProcessPlayer(Character you, Character ai)    {        Console.WriteLine("What do you want to do? You can ATK or DEF.");        int maxturns = 3;        string command = null;        for(int i = 0; i < maxturns; i++)        {            command = Console.ReadLine();            if(command.ToUpper() == "ATK")            {                you.Attack(ai);                return;            }            if(command.ToUpper() == "DEF")            {                if(you.Stance != 0)                {                    Console.WriteLine("Stance has already been set.");                    break;                }                you.SetStance(1);                return;            }            Console.WriteLine("{0} chances left", maxturns - (i + 1));        }                Console.WriteLine("Turn forfeited.");    }    public void StatusReport(Character ai, Character player)    {        Console.WriteLine("You now have {0} HP. The enemy has {1} HP.", player.Hp, ai.Hp);    }    public void EnterGameMode(Character ai, Character player)    {        Console.WriteLine("==========================================================");        Console.WriteLine("Welcome to SimpleRPGExample");        Console.WriteLine("==========================================================");        Random rand = new Random();        Character monster = ai;        Character hero = player;        for (int i = 0; i < 4; i++)            Console.WriteLine();        Console.WriteLine("Get ready! The computer goes first!");        while (true)        {            ProcessAI(monster, hero, rand);            StatusReport(ai, hero);            if (hero.KOED)            {                Console.WriteLine("You were defeated.");                break;            }            ProcessPlayer(hero, monster);            StatusReport(ai, hero);            if (ai.KOED)            {                Console.WriteLine("You were victorious.");                break;            }        }        Console.WriteLine("Thanks for playing! GAME OVER!");    }}class RPG{    static void Main()    {        Character player = new Character();        Character monster = new Character();        Game game = new Game();        game.EnterGameMode(monster, player);    }}
Quote: Original post by Knuckler
JWalsh posted a example of expressions using components of RPGs. I wanted to see if I could expand on that. Despite programming in C++ on and off for seven years, this is the first time I've ever done anything related to "game programming." It's a very very very (I can't stress "very" enough) basic battle system. It actually could have ended up nicer. I wanted to use events to handle when a player was K.Oed. But it was 2:00 a.m in the morning, and I wanted it finished "now," so I took the easy way out. Just sharing it with ya'll:

*** Source Snippet Removed ***

Magic numbers bad, mkay?
The first thing that popped out at me was this switch...with these funny magic numbers. Stance = 2? Huh? What the hell is stance, and what the hell does 2 have to do with it. Use enumerations. Secondly, you expose a stance property with just get, and then proceed to define a function to SET the stance. Use the set ability of properties. You also have this boolean for being KOED, but the condition for that is simply hp <= 0 (and the naming violates the recommended naming scheme by MS btw), so you can eliminate that boolean entirely.

I could go on, but I won't. One of the biggest problems with "finished now" things is that they tend to end up in even worse shape later on. Those quick hacks that you do today will remain tomorrow, and you'll compound upon them later by trying to do things quickly.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Yes.
Mike Popoloski | Journal | SlimDX
Quote: Original post by Mike.Popoloski
When this workshop first started, I assumed that having this nice C# Workshop forum at the top of the list would let people post different topics depending on the questions they were having, and then others could answer them, or see if their question was already posted somewhere else. Why isn't posting allowed in this forum?


Hi Mike,

The problem with just putting a forum up for everyone to post threads, is there's no sense of organization. People would be unable to determine what week the thread necessarily went with, or what difficulty level the question is.

The workshop is designed to coincide with the text, so anyone who has a question on the specification can easily locate the designated thread designed for posting questions on the related subject matter here in the workshop. Also, the idea is that if one person has a question, then it's likely that several people will have the same question. It works best if people follow the chapter threads closely.

People are currently unable to post threads in the workshop, because the intention is there is 1 thread per week, and then 1 thread per project. This nicely divides conversation based on the related chapters.

However, this is a learning process. The C# Workshop was based upon the C++ workshop which was formatted the same way. Unfortunately, or fortunately - depending on how you look at it, while the C++ Workshop got on average 35-50 posts per week, with week 1 and project 1 getting over 150 posts, the C# workshop has gotten over 300 posts in the first WEEK!

It's obvious that we're sinking under our own success. As I mentioned above, Superpig is looking at making a hybrid solution. The workshop is still broken up into nicely organized weeks and projects, but instead of it being 1 THREAD per week, it will be FORUM per week. This would allow people to post as many threads as they like within each of individual weeks. In essence, it provides the organization necessary for a sequential workshop, while also allowing people to freely create threads for easy reference.

I will speak with Superpig again to see how progress is going. Either way I will be posting the Week 2 thread within the next few days. I'm not sure when, exactly, because I will be out of town Friday afternoon to Tuesday night. I may post the thread before I leave, or via my laptop while out of town.

Cheers!
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
Quote: Original post by Washu
Quote: Original post by Knuckler
JWalsh posted a example of expressions using components of RPGs. I wanted to see if I could expand on that. Despite programming in C++ on and off for seven years, this is the first time I've ever done anything related to "game programming." It's a very very very (I can't stress "very" enough) basic battle system. It actually could have ended up nicer. I wanted to use events to handle when a player was K.Oed. But it was 2:00 a.m in the morning, and I wanted it finished "now," so I took the easy way out. Just sharing it with ya'll:

*** Source Snippet Removed ***

Magic numbers bad, mkay?
The first thing that popped out at me was this switch...with these funny magic numbers. Stance = 2? Huh? What the hell is stance, and what the hell does 2 have to do with it. Use enumerations. Secondly, you expose a stance property with just get, and then proceed to define a function to SET the stance. Use the set ability of properties. You also have this boolean for being KOED, but the condition for that is simply hp <= 0 (and the naming violates the recommended naming scheme by MS btw), so you can eliminate that boolean entirely.

I could go on, but I won't. One of the biggest problems with "finished now" things is that they tend to end up in even worse shape later on. Those quick hacks that you do today will remain tomorrow, and you'll compound upon them later by trying to do things quickly.


The stance field represents the mode of combat a character can be in. 0 is neutral stance. 1 is defensive stance (take and deal less damage). 2 is berserker stance (take and deal more damage). An enum is a better choice for representing the types of stances. I see that "NOW." It's a feature of C++ I never used extensively. For me it's just not as obvious to use such a feature compared to a more seasoned programmer. Especially at 2 in the morning.

Thanks you for your advice, Washu. The code could have came out a bit nicer if I was in a clearer state of mind. I'm going to rewrite it for myself to see if it can come out better. I'm definitely going to take your advice about "finished now" projects to heart for future programs.

I keep trying to use arrays but i cant seem to get 1 to work. I cant initialie and refer to it.
Here is what i got:
    class MapEngine    {        private byte xMaxArray = 40;        private byte yMaxArray = 40;        static string[,] MapArray;        public byte ModxMaxArray        {            get { return xMaxArray; }            set { xMaxArray = value; }        }        public byte ModyMaxArray        {            get { return yMaxArray; }            set { yMaxArray = value; }        }                public void InsterItem(string Item, byte X, byte Y)        {            MapArray.SetValue(Item, X, Y);        }        public string ReadItem(byte X, byte Y)        {            return MapArray.GetValue(X, Y);        }    }    class Unit    {        private string ID;        private string Type;        private string Status;        private int pHealth;        private int pAttack;        private int pDefense;        private int pCharge;        private int pMorale;        private int Range;        private int Speed;        private byte Posx;        private byte Posy;        private int Angle;        public void Die()        {            pHealth = 0;            Status = "Dead";            MapArray.InsertItem("Empty", Posx, Posy);        }        public void Move(string Where, int Heading)        {            Angle = Heading;            switch (Where)            {                case "Forward":                    if (MapArray.ReadItem(Posx, (Posy + 1)) = "Empty")                    {                        if (Posx != 60)                        {                            MapArray.InsertItem("Empty", Posx, Posy);                            Posy += 1;                            MapArray.InsertItem(ID, Posx, Posy);                            Status = "Moving Forward!";                        }                        else Status = "We cant Advance Anymore!";                    }                    else Status = "We can't advance, the enemy is holding that position!";                    break;            }        }   }

I get the following errors:
The name 'MapArray' does not exist in the current context.
I am having a hard time understanding how to Create, Construct, use, refer, set and get values from an array.

This topic is closed to new replies.

Advertisement