How do I detect key presses

Started by
14 comments, last by GameDev.net 18 years, 4 months ago
I am trying to learn C++ and am trying to make a pong game. The problem I am having is that I am not sure how to detect key presses so I made a little program to try to figure it out with. All that it does is display a grid of O's and I should be able to move the X around in them but I dont think my key presses are being detected. If any one can tell me what I am doing wrong or a better way to detect key presses I would really like it. Here is the code:

#include <iostream>
#include <conio.h>
using namespace std;

void printBoard();

void addBall();

void testKey();

const int ROWS = 10;
const int COLUMNS = 10;
int X = 5;
int Y = 5;

char board[ROWS][COLUMNS] = { {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                              {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'} };

int main()
{

while (true)
{
addBall();

printBoard();

testKey();

system("cls");

}
return 0;
}

void printBoard()
{


for (int i = 0; i < ROWS; ++i)
{
    for (int j = 0; j < COLUMNS; ++j)
        cout << board[j];
   cout << endl;

}
}
void addBall()
{    
     board[X][Y] = 'X';
}
     
void testKey()
{
#define    ENTER    13
#define    ESC    27
#define    UP    72
#define    DOWN    80
#define    LEFT    75
#define    RIGHT    77
#define    BACKSPACE    8
#define    TAB    9
#define    SPACE    32

int count = 0;
char key;
while(count < 1)
    {
    count += 1;
    
    if (kbhit())        
        {
        key=getch();    
        
        if (key==UP)   
        board[X][Y] = 'O';
        Y= Y + 1 ;
        
        if (key==DOWN)   
        board[X][Y] = 'O';
        Y = Y - 1;
        
        if (key==RIGHT)   
        board[X][Y] = 'O';
        X = X + 1;
        
        if (key==LEFT)   
        board[X][Y] = 'O';
        X = X - 1;
        }
        
        
    }
     
}



Advertisement
First of all, this might not apper helpful at all, but actually trying to do a game such as pong in the console is an exercise in frustration. If you feel you are up to it, you might consider learning a 2D API such as SDL.

Now, for the more helpful bit, if you are programming under Windows, you might consider looking GetAsyncKeyState() up in google.
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style
If you are stuck in dos, you will eventually want to write your own
ISR to handle the keyboard.
That way you get rid of the "repeat" delay that comes with getch()
if it's windows were talking about, do it in the window procedure.

bool keys_[256];

LRESULT CALLBACK WndProc (HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_KEYDOWN:

keys_[wParam] = true;
return 0;

case WM_KEYUP:

keys_[wParam] = false;
return 0;

default:
return DefWindowProc (hWnd, message, wParam, lParam);
}
}

that will put the key_[key] as true when it's pressed, and false when its not pressed, so you could have a function in your program loop that does like

if(key_[VK_DOWN] == true)
Player->duck();

if(key_[VK_UP] == true)
Player->jump();

or something like that. To me, it's always been very responsive, and lets you use many keys at a time, like down + right, or down + left, or whatever you want. You could get even fancier if you want. Sky is tha limit :)
|aaap.penopticon.com| My website, including game projects. Collaboration/comments are welcome, please visit :)
Quote:
if (key==UP)
board[X][Y] = 'O';
Y= Y + 1 ;

if (key==DOWN)
board[X][Y] = 'O';
Y = Y - 1;

if (key==RIGHT)
board[X][Y] = 'O';
X = X + 1;

if (key==LEFT)
board[X][Y] = 'O';
X = X - 1;


Unfortunately you forgot to wrap those 'if' statements with braces, with a little correction this may help:

if (key == UP)
{
board[X][Y] = 'O';
Y= Y + 1 ;
}

and even better, I suggest using switch statement for literal numbers checking like this. You did know how to implement switch, didn't you ?.
--> The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones <--
If you are on windows, you can just use GetAsyncKeyState().

For example to check for the escape key:
#include <windows.h>int main(){   // Obviously, the loop could also be: while(!GetAsyncKeyState(VK_ESCAPE));   while(1)   {   if(GetAsyncKeyState(VK_ESCAPE))      break;   }   return 0;}

Use MSDN. Virtual-Key Codes - a list of all the keys.
skulldrudgery--A tricky bit of toil
It was just a stupid mistake by me for not putting braces on the if staments. I am writing the pong game write now and when I am done I will post the code. Thanks for all your help.
If you don't mind a bit of work, then check out NeHe's tutorials, http://nehe.gamedev.net, the tutorials explain how to use basic key presses, (it's a start). They also cover alot more.. like collision detection, which might come in handy for pong.
Here what I have so far. The problem is that the ball only moves when a key is pressed. Does anyone know what I did wrong.

#include <iostream>#include <conio.h>using namespace std;void addPaddle(); //adds player paddlevoid addPaddleTwo(); //adds computer paddlevoid addBall();void testKey();void printMatrix();void removeLast(); // remove everything fort he matrix that isnt supposed to be there.const int ROWS = 20;const int COLUMNS = 20;int X = 5; //the new balls positionint Y = 5; //the new balls positionint key; // test if a key got hitint XX; //origanals balls positionint YY; // origanal balls postionint A = 5; //first peice of players paddleint B = 6; //second peice of players paddleint C = 7; // third peice of players paddleint D = 8; // fourth pies of players paddleint AA;int BB;int CC;int DD;int EE;int FF;int GG;int HH;bool leftRight; //true == left false == rightbool upDown; //true == up false == downbool straight; //true == straight down false == nothingchar matrix[ROWS][COLUMNS] = { {'#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},                               {'#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'} };                               int main(){ while (true){addBall();addPaddle();addPaddleTwo();printMatrix();testKey();testKey();cout << endl;cout << key;system("cls");removeLast();}return 0;}void addPaddle(){     matrix[18][A] = '=';     matrix[18] = '=';     matrix[18][C] = '=';     matrix[18][D] = '=';          AA = A;     BB = B;     CC = C;     DD = D;}void testKey(){key = getch();{if (AA != 1){if (key == 75)//left{   A = A - 1;   B = B - 1;   C = C - 1;   D = D - 1;}}if (DD != 18){if (key == 77)//right {   A = A + 1;   B = B + 1;   C = C + 1;   D = D + 1;} }   }}void printMatrix(){   for (int i = 0; i < ROWS; ++i){    for (int j = 0; j < COLUMNS; ++j)        cout << matrix[j];   cout << endl;}}void removeLast(){     matrix[XX][YY] = ' ';     matrix[18][AA] = ' ';     matrix[18][BB] = ' ';     matrix[18][CC] = ' ';     matrix[18][DD] = ' ';          matrix[1][EE] = ' ';     matrix[1][FF] = ' ';     matrix[1][GG] = ' ';     matrix[1][HH] = ' ';          matrix[1][0] = '#';     matrix[2][0] = '#';     matrix[3][0] = '#';     matrix[1][19] = '#';         }void addBall(){     srand(time(0));          int direction = (rand() % 3) + 1; //stores 1, 2, 3      int upORdown = (rand() % 2) + 1; //stores 1, 2          XX = X;     YY = Y;          matrix[X][Y] = 'O';          if (X == 17 && Y == AA)     upDown = true;          if (X == 17 && Y == BB)     upDown = true;          if (X == 17 && Y == CC)     upDown = true;          if (X == 17 && Y == DD)     upDown = true;          if (X == 2 && Y == EE)     upDown = false;          if (X == 2 && Y == FF)     upDown = false;          if (X == 2 && Y == GG)     upDown = false;          if (X == 2 && Y == HH)     upDown = false;                         if (Y == 1)     leftRight = false;               if (Y == 18)     leftRight = true;                    if (X == 18)     {         X = 10;         Y = 10;     }          if (X == 1)     {           X = 10;           Y = 10;     }          if (upDown == true)     X = X - 1;          if (upDown == false)     X = X + 1;               if (leftRight == true)     Y = Y - 1;          if (leftRight == false)     Y = Y + 1;     }void addPaddleTwo(){                        EE = (Y - 1);     FF = Y;     GG = (Y + 1);     HH = (Y + 2);                  if (EE == 1)     {     EE = EE + 1;     FF = FF + 1;     GG = GG + 1;     HH = HH + 1;     }     if (HH == 18)     {     EE = EE - 1;     FF = FF - 1;     GG = GG - 1;     HH = HH - 1;     }     matrix[1][EE] = '=';     matrix[1][FF] = '=';     matrix[1][GG] = '=';     matrix[1][HH] = '=';}
You're only moving the ball when a key is pressed. Perhaps you could make some kind of a UpdateBall() function that moves the ball every second or so?

Good luck.

This topic is closed to new replies.

Advertisement