Question What went wrong?

porkshopp

Active member
Joined
Apr 13, 2019
Messages
26
Location
Sweden
Programming Experience
Beginner
I have this program in which I want to move around in a grid of the players choosing. When moving from the first position of the last row it gives me an error message since the value is outside of the size of the array, I have no idea how to fix it. And also, how can I make it move automatically when I have pressed a button, so I don't have to press enter between for the press to register?

C#:
using System;
namespace ConsoleApp2
{
    class Program
    {
        static void Print(int[] board, int Pos, int rGrid)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            int i = 0;
            while (i < (rGrid*rGrid))
            {
              
                board[Pos] = 5;
                if ((i + 1) % rGrid == 0)
                {
                    if (board[i] == board[Pos]) Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine(board[i]);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                }
                else
                {
                    if (board[i] == board[Pos]) Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(board[i]);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                }
                  
              
                i++;
            }
          
        }
        static void Clear(int[] board, int rGrid)
        {
            int h = 0;
            while (h < (rGrid*rGrid))
            {
                board[h] = 0;
                h++;
            }
        }
    
    static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.WriteLine("Enter CellGrid");
            string grid = Console.ReadLine();
            int rGrid;
            if (int.TryParse(grid, out rGrid))
            {
                Console.Clear();

                int Pos = rGrid;
                int[] board = new int[(rGrid*rGrid)];
                int j = 0;
                while (j < (rGrid*rGrid))
                {
                    board[j] = 0;
                    j++;
                }

            Choose:
                int i = 0;
                while (i < 10)
                {
                    Print(board, Pos, rGrid);
                    string answer = Console.ReadLine();
                    Clear(board, rGrid);
                    if (answer == "w")
                    {
                        if ((Pos - rGrid) >= 0) Pos -= rGrid;
                        else Pos += ((rGrid*rGrid)-rGrid);
                    }
                    else if (answer == "s")
                    {
                        if ((Pos + rGrid) <= (rGrid * rGrid)) Pos += rGrid;
                        else
                        {
                          
                          
                                Pos -= ((rGrid * rGrid) - rGrid);
                          
                        }
                    }
                    else if (answer == "d")
                    {
                        if ((Pos + 1) > ((rGrid*rGrid)-1))
                        {
                            Pos = 0;
                        }
                        else Pos++;
                    }
                    else if (answer == "a")
                    {
                        if ((Pos - 1) < 0)
                        {
                            Pos = (rGrid*rGrid)-1;
                        }
                        else Pos--;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("[Invalid Syntax!]");
                        Console.ReadKey();
                        Console.Clear();
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        goto Choose;
                    }
                    Console.Clear();
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Invalid Syntax!]");
                Console.ReadKey();
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Yellow;
                Main(null);
            }
         


        }
    }
}
 
Last edited by a moderator:
The reason why you have to press "Enter" is because you are using ReadLine(). That waits for an entire line of text to be entered. The end of a line is denoted by pressing the "Enter" key.

You should be using ReadKey() like you seem to be using in other places in your code.
 
As for the array out range issue, recall that C# arrays are zero based. You condition on line 75 does not take this into account.

For example, let rGrid be 3. So when you end up creating an one dimensional array with 9 elements because 3*3 == 9, and set the initial Pos to 3. When you first press 's' to go down 3+3 == 6. The next time 6 + 3 == 9. But your array is only good for indices 0 to 8.

Why are you making things hard for yourself by using a one dimensional array? Why not create a 2 dimensional array right off the bat? That way you don't have to do all these column and row calculations to determine the next position depending on whether moving on the X or Y axis.

As an aside, be aware that not all keyboards have "WASD" setup as an inverted T. For example, on my Dvorak keyboard:
500px-KB_United_States_Dvorak.svg.png
 
I have thought about c# being 0-based, but I still havnt come up with a possible fix.
I haven't learned about 2 dimensional arrays, which I will do after this project.
 
And also, how do I use ReadKey()?
Maybe start by reading the documentation for that method. It says that it returns a ConsoleKeyInfo object, not a char, so the next step would be to read about that type and how you get the info you need form it. Reading the relevant info should ALWAYS be the first step.
 
Ok, so I did. I used this code but it only lets me type "w" in the console as input but every other symbol isn't accepted. I tested with only w since it was easier.
C#:
using System;
namespace Move_R2
{
    class Program
    {
        static void Print(string[,] board, int a, int xPos, int yPos)
        {
            for (int i = 0; i < a; i++)
            {
                for (int j = 0; j < a; j++)
                {
                    if (board[i, j] == board[yPos, xPos])
                    {
                        if ((j + 1) % a == 0)
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine(board[i, j]);
                            Console.ForegroundColor = ConsoleColor.Yellow;
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.Write(board[i, j]);
                            Console.ForegroundColor = ConsoleColor.Yellow;
                        }
                    }
                    else
                    {                    
                        if ((j+1) % a == 0)
                        {
                            Console.WriteLine(board[i, j]);
                        }
                        else Console.Write(board[i, j]);
                    }
                }
            }
        }
        //prints every value in board[] and every a/2,a/2 is green (Player position).
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            const int a = 5;
            int xPos = a/2;
            int yPos = a/2;        
            string[,] board = new string[a, a];
        // creates grid in R2
        Start:
            Console.Clear();
            for (int i =0; i<a; i++)
            {
                for (int j = 0; j<a; j++)
                {
                    board[i,j] = "O";
                }
            }
            //Assigns all values to "O"                
            board[yPos, xPos] = "X";
            Print(board, a, xPos, yPos);
          
while (Console.ReadKey().Key == ConsoleKey.Enter)
       
            {
                if ((yPos - 1) >= 0)
                {
                    yPos--;
                }
                else yPos = (a - 1);
}
         
            goto Start;
        }
    }
}
 
Last edited by a moderator:
Did you debug the code, i.e. set a breakpoint and step through it line by line? If not, you should do that now. Once you have, if you still need help, tell us EXACTLY where and how the code behaves differently to your expectation.
 
Ok, so I did. I used this code but it only lets me type "w" in the console as input but every other symbol isn't accepted. I tested with only w since it was easier.
[/code]
Actually, it's not that it only accepts "w". It's because you code on lines 63-67 is what would have happened if the "w" is pressed. Your only condition on line 60 is that as long as the "Enter" key is not pressed, then keep on looping. Once any other key other than "Enter" is pressed, lines 63-67 treat the input as if the user had wanted to move upward. If you had additional logic to look at what key was actually pressed, you could have different behavior.
 
Oww, my bad. I copied wrong. I hade written ConsoleKey.W instead. But when it runs I get the same outcome as stated above, I don't understand whats wrong.
 
Step through your code with a debugger and it should make things should be more clear as you watch what is happening in relation to the data that your program is getting.
 
Back
Top Bottom