Testing if a specific character is present in a chosen direction from another character in the console

11 Views Asked by At

I have made a small piece of code that creates a field made up of '.' and want to set the '#' as a form of a barrier. I have set the player location to be a variable and be represented by a '*' and wrote a bit of code that allows user input to choose the direction in which it will move on the field. I am struggling to do a check when a direction is pressed, if there is a '#' it will display a message saying that you can not move in that direction otherwise proceed as normal. Whilst I understand that this question might have been answered I can not find an answer to my issue or am unable to execute it to my given example.

using System;

class TestGame
{
    static void Main(string[] args)
    {
        int playerY = 2; //sets the y coordinate of the player
        int playerX = 2; //sets the x coordinate of the player
        bool gameRunning = true;

        while (gameRunning)
        {
            // Display the game board
            for (int y = 0; y < 12; y++) //sets y to 0, checks if y is less than 12, executes commands, adds 1 to y
            {
                for (int x = 0; x < 40; x++) //same as above but for x
                {
                    if (y == playerY && x == playerX) //checks if y == to playerY and x ==player X
                    {
                        Console.Write("*"); //for when, if it is then it outputs a *
                    }
                    else if (y == 2 && x == 12) //for when, if y and x are equal to a specific value
                    {
                        Console.Write("@"); //execute this
                    }
                    else if (y == 0 || x == 0 || y == 11 || x == 39)
                    {
                        Console.Write("#");
                    }
                    else
                    {
                        Console.Write("."); //otherwise just have a dot
                    }
                }
                Console.WriteLine(); //empty space
            }

            // Get user input
            Console.WriteLine("Enter move: A D W S");
            string userInput = Console.ReadLine();
            switch (userInput) //checks for user inputs
            {
                case "A":
                    playerX--;
                    break;
                case "D":
                    playerX++;
                    break;
                case "W":
                    playerY--;
                    break;
                case "S":
                    playerY++;
                    break;
                default:
                    Console.WriteLine("Invalid Key"); //defaults to this if any other key is pressed
                    break;
            }
        }

    }
}

}

0

There are 0 best solutions below