frankcollins3 / fcc-mcsft-cSharp

FreeCodeCamp & Microsoft C# course:
1 stars 0 forks source link

handling non directional Keydowns to restrict gameplay [11:10pm] #44

Closed frankcollins3 closed 1 year ago

frankcollins3 commented 1 year ago

attempting to do: exception handler for ConsoleGame player movement Screen Shot 2023-09-12 at 11 08 17 PM Screen Shot 2023-09-12 at 11 07 57 PM

error: no errors no attempts yet just mapping possibilities.

proposed approach: instead of switch, use if-elseif-else statements so: else block can catch any non directional key and terminate gameplay.

minimum viability: just check the "A" key to see if 1 key can work at first.

possible improvements:

frankcollins3 commented 1 year ago

an attempt at using if statements returns this error: Screen Shot 2023-09-12 at 11 13 47 PM

/CsharpProjects/TestProject/Program.cs(75,17): error CS0428: Cannot convert method group 'ReadKey' to non-delegate type 'bool'. Did you intend to invoke the method?

Screen Shot 2023-09-12 at 11 13 52 PM [11:15pm]

frankcollins3 commented 1 year ago

the microsoft provided example has an if statement without any brackets // if (Console.ReadKey) [11:18pm]

frankcollins3 commented 1 year ago

/Program.cs(95,9): error CS0029: Cannot implicitly convert type 'System.ConsoleKey' to 'bool' [11:20pm]

👎     if (Console.ReadKey(true).Key)              // if arg is technically a bool and returning type error 
    {
            if (ConsoleKey.UpArrow)
        {
        playerY--;
        break;
        }
            else if (ConsoleKey.DownArrow)
        {
        playerY++;
        break;
        }
            else if (ConsoleKey.LeftArrow)
        {
        playerX--;
        break;
        }
            else if (ConsoleKey.RightArrow)
        {
        playerX++;
        break;
        }
            else if (ConsoleKey.RightArrow)
        {
        playerX++;
        break;
        }
            else
        {
            Console.WriteLine("yeah what else");
        }
    }

[11:21pm]

frankcollins3 commented 1 year ago

wow Screen Shot 2023-09-12 at 11 23 45 PM /Program.cs(93,14): error CS0023: Operator '!' cannot be applied to operand of type 'ConsoleKey' [11:24pm]

frankcollins3 commented 1 year ago

figured this much myself but then encountered typing errors. maybe chatGPT did something with it i wasn't: Screen Shot 2023-09-12 at 11 25 44 PM [11:26pm]

frankcollins3 commented 1 year ago

redeeming factor is I understood this but still couldn't get it to work. chatGPT code works:

    ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key == ConsoleKey.UpArrow)
{
    playerY--;
}
else if (keyInfo.Key == ConsoleKey.DownArrow)
{
    playerY++;
}
else if (keyInfo.Key == ConsoleKey.LeftArrow)
{
    playerX--;
}
else if (keyInfo.Key == ConsoleKey.RightArrow)
{
    playerX++;
}
else if (keyInfo.Key == ConsoleKey.Escape)
{
    shouldExit = true;
}
else
{
    Console.WriteLine("Press directional keys only, please!");
}

[11:28pm]