Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I read up, down , left and Right keys ?

Status
Not open for further replies.

IMAUser

Technical User
May 28, 2003
121
CH

Hi ,

Am trying to write my first game in C. Its the common "Snake" game. I have managed to create a line and move it, but how do I read the user input of up , down , left and right keystrokes and move the snake accordingly.

Or do you know if the source code of this game is available on the net somewhere, I can maybe look at it and get some help.

Many Thanks
 
Reading extended keys, and reading keys without waiting for say enter to be pressed is dependent on your operating system and compiler.


--
 
Thanks Salem for the response.

But I am using Turbo C and I wanted to do something like

if uparrow then
move up
else if down arrow then
move down
else if left arrow then
move left
else if right arrow then
move right
end if;

This piece of code will go within a loop which will keep running endlessly or till the snake hits the border or itself.

So for the if statement , what should I check. Is there a octal value or a ASCII value which I can check. And since I am not going to wait for a key to be hit, how do I know when the user hits a key.

Thanks again

 
Are you programming under DOS/WINDOWS? if so,
I think you should make a testing program for keys, like this:

#include<conio.h>
#include<stdio.h>
int main()
{
int c1 = getch();
int c2;
c1 = getch();
if(c1)
{
printf(&quot;the ASCII code of the key is {%d}\n&quot;, c1);
}else
{
c2 = getch();
printf(&quot;the codes of the functional key are {0;%d}\n&quot;, c1);
}
return 0;
}
Use the program above to test keys if you don't know the ASCII code of some of them.
So, when you press a character key(for exampla a, b, c, <enter>, <space>, <esc>...), in the keyboard buffer is placed a single character. If you press a functional key, in buffer are paced two characters(<some arrow>, <f1..fXXX>, <ins>...). The first one is 0. If you get 0 it means you should extract the next character.

The next step is waiting for a key to be poressed. The function kbhit() return 0 if no key is pressed. So use

int run = 1;
while(run)
{
while(khhit())
{
c1 = getch();
if(c1)/*process a simple key*/{switch(c1......}
else /*process a functional key*/
{c2 = getch();
switch(c2.....
}
}
/*if you want to exit set run to 0*/
}

Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top