C++ Console : Keyboard Input for Games

Usually we need arrow keys input for simple games like luddo, tic-tac-toe or any board game. Here is a simplified code for getting input from arrow keys of keyboard. As you read code you can easily edit it for your own choice buttons and return values of the input function.
 #include <iostream>  
 #include <windows.h>  
 #include <conio.h>  
 using namespace std;  
 int getArrowKeyInput();  
 void main(){  
      char user = getArrowKeyInput();  
      while (user != 'e'){  
           cout << user << endl;  
           user = getArrowKeyInput();  
      }  
      system("pause");  
 }  
 int getArrowKeyInput(){  
      int input = _getch();  
      char return_value;  
      if (GetAsyncKeyState(VK_DOWN)){  
           _getch();  
           return_value = 'd';  
      }  
      else  
      if (GetAsyncKeyState(VK_RIGHT)){  
           _getch();  
           return_value = 'r';  
      }  
      else  
      if (GetAsyncKeyState(VK_LEFT)){  
           _getch();  
           return_value = 'l';  
      }  
      else  
      if (GetAsyncKeyState(VK_UP)){  
           _getch();  
           return_value = 'u';  
      }  
      else  
      if (input == 13){  
           return_value = 'e';  
      }  
      return return_value;  
 }  
     There is no specific output to show. Run this code yourself and see the output.

Important points to note:
  • VK_ specifies an arrow key and it is easy to understand
  • the condition where input is being checked against number 13 is basically checking that if "enter" key is pressed. You can put any key's ascii value in here to check if that specific key is pressed.

Comments

Popular posts from this blog

C++ Console : Basic Graphic Techniques

C++ Console : Change Font Size

C++ Console : Color