Sign in to follow this  
Eric_Harstad

How do I detect key presses

Recommended Posts

Eric_Harstad    122
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[i][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;
        }
        
        
    }
     
}



Share this post


Link to post
Share on other sites
jfclavette    1058
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.

Share this post


Link to post
Share on other sites
pulpfist    528
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()

Share this post


Link to post
Share on other sites
AAAP    137
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 :)

Share this post


Link to post
Share on other sites
Skeleton_V@T    512
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 ?.

Share this post


Link to post
Share on other sites
skulldrudgery    253
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.

Share this post


Link to post
Share on other sites
Eric_Harstad    122
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.

Share this post


Link to post
Share on other sites
frogtag    121
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.

Share this post


Link to post
Share on other sites
Eric_Harstad    122
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 paddle

void addPaddleTwo(); //adds computer paddle

void 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 position
int Y = 5; //the new balls position
int key; // test if a key got hit
int XX; //origanals balls position
int YY; // origanal balls postion
int A = 5; //first peice of players paddle
int B = 6; //second peice of players paddle
int C = 7; // third peice of players paddle
int D = 8; // fourth pies of players paddle
int AA;
int BB;
int CC;
int DD;
int EE;
int FF;
int GG;
int HH;



bool leftRight; //true == left false == right
bool upDown; //true == up false == down
bool straight; //true == straight down false == nothing

char 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][B] = '=';
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[i][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] = '=';
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
time is a lot more complicated :/ you'll want to write a timer class for your project that is consistently accurate.

Share this post


Link to post
Share on other sites
pulpfist    528
If you have a dos project you can get the cpu ticks since program start pretty easy. This value is updated 18.2 times per seconds (can be programmed to use a higher freq.)
Correct me if Im wrong.


long start_time, current_time;

game_loop()
{
start_time = *(long far*)0x0000046CL;

...do work here...

do {
current_time = *(long far*)0x0000046CL;
} while(current_time < start_time + 18); // wait ~1 sec.
}


Share this post


Link to post
Share on other sites
wortel    174
Get a nice library, i recommend allegro, i think it's probably the most underrated game library out there,especially for beginners. It has nice examples & very good documentation.

Good luck

Share this post


Link to post
Share on other sites
Daedalus AI    100
Had a quick scan through this discussion, so sorry if I've repeated someones advice.

If it's windows you're using, an easy way is to use kbhit();


...
while( true )
{
if ( kbhit() == true )
{
/* Code goes here */
}
}
...



To retrieve what key or character was pressed; you can use getch().

This doesn't work in Linux as far as I know.

Daed.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster


If you are stuck using getch() to get the special keys like UP, DOWN, PAGEUP, PAGEDOWN, etc. you need to make one more call to getch() but only on certain conditions..

[code]
int key1, key2;
if (kbhit()){
key1 = getch();
if (key1 == 0){ // A special key was hit.
// now we get the key that was pressed
key2 = getch();
cout <

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this