lundi 22 mai 2017

Random movement of char in console c#

I made a maze game in a console application and by using keys I can control character to leave the maze. Now I want to figure out how to automate that process So that my character can go by random directions and try to find the way out. Here is my class. The problem is in the randomMovement Method.

class Player: Maze
{
    public int x = 1;
    public int y = 1;


    public string playerName;

    public static void printMv() {
        while (true)
        {
            for (int i = 0; i < 15; i++)
            {


                Console.Clear();
                mazeDev();

                Console.Write("0");
                Thread.Sleep(1000);
            }
        }
    }


    public static void movementByUser()
    {

        int x = 1, y = 1;
        while (true)
        {

            Console.Clear();
            mazeDev();
            Console.CursorLeft = x;
            Console.CursorTop = y;
            Console.Write("0");


            ConsoleKeyInfo mv = Console.ReadKey();
            if (mv.Key == ConsoleKey.Escape) break;
            if (mv.Key == ConsoleKey.A && mazeBluePrint[y, x - 1] == 0) {
                x--;
            }
            if (mv.Key == ConsoleKey.D && mazeBluePrint[y, x + 1] == 0)
            {
                x++;
            }
            if (mv.Key == ConsoleKey.W && mazeBluePrint[y - 1, x] == 0)
            {
                y--;
            }
            if (mv.Key == ConsoleKey.S && mazeBluePrint[y + 1, x] == 0)
            {
                y++;
            }
        }
    }
    public static void randomMovement()
    {
        Random randMove = new Random();

        int x = 1;
        int y = 1;

        int irandom = randMove.Next(4);
        Console.CursorLeft = x;
        Console.CursorTop = y;

        if (irandom == mazeBluePrint[y, x - 1])
        {
            x--;
            printMv();

        }
        else if (irandom == mazeBluePrint[y, x + 1])
        {
            x++;
            printMv();
        }
        else if (irandom == mazeBluePrint[y - 1, x])
        {
            y--;
            printMv();
        }
        else
        {
            y++;
            printMv();
        }


    }
}

}




Aucun commentaire:

Enregistrer un commentaire