Click here to Skip to main content
15,891,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am at a wall with this code, I need help figuring out what it is exactly asking me to do. I just need some examples of how to do this. Thanks

C#
   namespace DelgateKeypress
{
    class Program
    {
        private static int x=20;
        private static int y=20;

        //TBD: You will need to define a data structure to store the association 
        //between the KeyPress and the Action the key should perform
       

        private static void Main(string[] args)
        {
            //TBD: Set up your control scheme here. It should look something like this:
            //   myControls.Add(ConsoleKey.W, Up)
            //   myControls.Add(ConsoleKey.S, Down)
            //or you can ask the user which keys they want to use
            //etc

          



            while (true)
            {
                Console.SetCursorPosition(x, y);
                Console.Write("O");

                var key = Console.ReadKey(true);


                int oldX = x;
                int oldY = y;


                //TBD: Replace the following 4 lines by looking up the key press in the data structure
                //and then performing the correct action
                if (key.Key == ConsoleKey.W) Up();
                if (key.Key == ConsoleKey.S) Down();
                if (key.Key == ConsoleKey.A) Left();
                if (key.Key == ConsoleKey.D) Right();

                Console.SetCursorPosition(oldX, oldY);
                Console.Write(".");


            }
        }

        private static void Right()
        {
            x++;
        }

        private static void Left()
        {
            x--;
        }

        private static void Down()
        {
            y++;
        }

        private static void Up()
        {
            y--;
        }
    }
}


Mainly the TBD parts I Don't understand what it is asking me to do. Thanks
Posted
Comments
[no name] 6-Dec-15 19:51pm    
Please detail what you have actually done so far beside posting here. A simple Google search will turn up lots of help including example code. That is largely what the assignment requires. Get out of your head the idea that your teacher, your next door neighbour or us should help you and learn to be self reliant. When you have a specific question present it here and it will be considered.
Member 12189919 6-Dec-15 20:17pm    
Instead of being a turd and coming here to try and assume anything you should read the question asked. Can anyone help me understand what is needed here. This is a "Hey any help would be appreciated" Not everyone has the privilege of being natural's at coding especially those who suffered brain injuries in Iraq and have trouble with recalling information or processing things at times. To the person who has posted some information I appreciate it.
[no name] 6-Dec-15 20:28pm    
Everyone is the same in this forum.
PIEBALDconsult 6-Dec-15 21:08pm    
Buy you a drink?
PIEBALDconsult 6-Dec-15 21:12pm    
"I Don't understand what it is asking me to do"
Neither do we; there's no way can, we don't know what the program is supposed to do. You probably know what the program is supposed to do, so you're better prepared to answer the question than we are. Can you at least tell us what it's _supposed_ to do?

This is your homework and you should solve it by yourself.

Here are some links with information that could be useful for you.

Delegates (C# Programming Guide)[^]

Using Delegates (C# Programming Guide)[^]

Delegates Tutorial[^]
 
Share this answer
 
Comments
Member 12189919 6-Dec-15 19:21pm    
I am not asking for someone to solve this for me, I am asking for help with solving it, understanding how this works, examples etc. I have an instructor who does not respond to questions so instead of cheating to get answers I would like to understand how some of this works and I happen to be more of a visual learned with examples.
George Jonsson 6-Dec-15 19:26pm    
Go through the links I provided and I think you will get a good understanding.
BillWoodruff 7-Dec-15 2:34am    
+5
ok, lets try another way - George Jonsson has given you good info, but you may still be scratching your head going wtf .. yes ?

Before we look at the 'TBD's" lets look at what your program is doing at the moment ...

(1) you're running a loop

C#
while (true)
{
  // Lots of stuff in here 
}


(2) in the loop you are reading a key/character from the keyboard

C#
var key = Console.ReadKey(true);


(btw - do you know what the ReadKey(true) does ? hint - have a look here https://msdn.microsoft.com/en-us/library/x3h8xffw(v=vs.110).aspx[^] )

(3) (getting to the guts)

if (key.Key == ConsoleKey.W) Up();
if (key.Key == ConsoleKey.S) Down();
if (key.Key == ConsoleKey.A) Left();
if (key.Key == ConsoleKey.D) Right();


so, if the key pressed is 'w', we are calling the function 'Up', if the key pressed is 's' we call the function 'Down'

Yes ? .. and whats wrong with this ? nothing really. But lets say you wanted to handle 26 keys - what would that look like ?

if (key.Key == ConsoleKey.W) Up();
if (key.Key == ConsoleKey.S) Down();
if (key.Key == ConsoleKey.A) Left();
if (key.Key == ConsoleKey.D) Right();
// More keys
if (key.Key == ConsoleKey.X) DoSomething();
if (key.Key == ConsoleKey.Y) DoSomethingElse();
// Ad nauseum...


Proper/Professional Programmers would hate a long line of if's testing for the keys - if you needed to add or remove valid keys, or change what keys do, or just keep the code tidy, there must be a better way ... (musnt there ?)

Ok, so, what your instructor is trying to lead you through is a path by which you can reduce the line of 'if key input equals this key then do that action' sort of thing

So, we are going to take a leap here .. lets say we could store all the valid keys and what happens when you push those keys in some kind of store. Then, when you get a key from the keyboard, instead of all those if's, you have maybe 3 lines, to check if the key is in the kind of store, and perform the action associated with the key

ok, so, now, its coming up to your turn - lets look at this first TBD ...

C#
//TBD: You will need to define a data structure to store the association 
//between the KeyPress and the Action the key should perform


What sort of data structure do you think we could use to store two values, such as a 'key' eg 'a' and some sort of action that we might want to do if the key 'a' was pressed ?? (.. now, there are many possible ways to do this, Im thinking of a very obvious one) ... so have a look through your notes, and see what you can come up with (reply back)
 
Share this answer
 
Comments
BillWoodruff 7-Dec-15 2:34am    
+5
I'll add a few comments to the useful answers here by George Jonsson and Garth Lancaster; I'll focus on the use of delegates. By the way, lots of smart people beginning C# (without a background in other languages where the equivalent of 'delegates exists) have trouble "getting" what delegates are about.

A delegate can be thought of as a template for a unit of executable code.

So, if we define: private delegate void KeyCommand(); In effect, we've "declared" a new 'Type, a prototype, a template that we can make instances from into which we can insert any method into ... as long as the method has the same signature as the delegate ... which means that the types of any return value and of parameters must be identical.

In this case, the signature is of a method which takes no parameters, and returns nothing (void).

Some find it helpful to recite the following when thinking of delegates: "The Delegate is a 'Type, to use it, we must have instances" :)

Since all your cursor movement methods have a signature which matches 'KeyCommand, any of them can be used as the "content" of an instance of the delegate.

So, we could write: KeyCommand up = Up;, and then anytime we executed up(); we'd be calling your method, 'Up.

The power of using delegates is when we wish to use executable code at run-time and we need the flexibility of using different executable code depending on ... whatever. So, we can define any number of delegate instances, bind them to method code that matches the signature of the delegate, and use them flexibly.

We can create a generic Dictionary that pairs ConsoleKey values (ConsoleKeyInfo.Key) with executable code by using the delegate
C#
// required 
using System.Collections.Generic;

// note the delegate must be defined outside any 'static context !
private delegate void KeyCommand();

// this can be defined in a static context
Dictionary<ConsoleKey, KeyCommand> KeysToCommands = new Dictionary<ConsoleKey, KeyCommand>
{
    {ConsoleKey.RightArrow, Right},
    {ConsoleKey.LeftArrow, Left},
    {ConsoleKey.DownArrow, Down},
    {ConsoleKey.UpArrow, Up}
};
Using this Dictionary, we can execute any method by using the ConsoleKey value to access the executable code: KeysToCommands[ConsoleKey.Up](); // executes 'Up

Note: when you use Console.ReadKey(true) the return value is an instance of the ConsoleKeyInfo object (struct). You get the ConsoleKey value from the ConsoleKeyInfo.Key property.

Beginning with C#3.0, anonymous delegates which can be written using Lambda notation were added to the C# language/compiler; so now, you can write this:
C#
Dictionary<ConsoleKey, KeyCommand> KeysToCommands = new Dictionary<ConsoleKey, KeyCommand>
{
    {ConsoleKey.RightArrow, () => { x++; }},
    {ConsoleKey.LeftArrow, () => { x--; }},
    {ConsoleKey.DownArrow, () => { y++; }},
    {ConsoleKey.UpArrow, () => { y--; }},
};
Understanding delegates and their flexibility is a powerful tool that you will find has many uses; delegates are the basis for C# multi-cast Events:
"Events and delegates are tightly coupled concepts because flexible event handling requires that the response to the event be dispatched to the appropriate event handler. An event handler is typically implemented in C# via a delegate."
Jessie Liberty "Learning C# 3.0" as quoted in Microsoft's re-publication of his Chapter 17 [^]
 
Share this answer
 
v6
Comments
George Jonsson 7-Dec-15 3:40am    
Good explanation.
+5
Garth J Lancaster 8-Dec-15 1:47am    
Nice work Bill - I was hoping the poster was following along and was going to answer me back - I think we lost him :-( I was going to post my working demo I cooked up for him, seems I dont need to now :-)

I had the final TBD as well, along the lines of

if (KeysToCommands.ContainsKey(key.Key)) KeysToCommands[key.Key].DynamicInvoke();

Love the lamdas - that was my first way of doing it, till I thought his instructor would chuck a mental !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900