will
will

Reputation: 13

How to run code when the user presses a specific key c#

how do I make this work properly? What do i need to include in my using at the top? And is this even possible?

internal class Program
{
    int money = 10;
    public void Water()
    {
        Console.WriteLine("You spent $5 on water");
        money -= 5;
    }
    static void Main(string[] args)
    {
        Console.WriteLine("To buy water press the w key");
        if(// w key is pressed)
        {
            Water();
        }

        //wait before closing
        Console.ReadKey();
    }
}

Upvotes: 0

Views: 56

Answers (2)

Miles
Miles

Reputation: 399

Maybe you meant something like this:

internal class Program
{
    static int money = 20;
    
    static void Main(string[] args)
    {
        Console.WriteLine(BuyWater());
    }

    public static string BuyWater()
    {

        while (money > 0)
        {
            Console.WriteLine("To buy water press the w key");
//this is where your pressed key comes in:
            if (Console.ReadKey(true).Key == ConsoleKey.W)      
            // (true) is for not showing the pressed key in the console
            {
                Console.WriteLine("You spent $5 on water");
                money -= 5;
            }

            Console.WriteLine("You have $" + money);

        }
        return "You have no money left";
    }
}

Upvotes: 1

Edgar
Edgar

Reputation: 11

Console.ReadKey do exactly what you need.

Console.WriteLine("Press w to buy water");

if (Console.ReadKey().Key == ConsoleKey.W)
    Water();

Upvotes: 0

Related Questions