Friday, May 21, 2010

C LANGUAGE: How do I use the kbhit function to make a snake program?

Just the simplest way possible. I'm a high school student and it doesnt need to be great. Thanks.

C LANGUAGE: How do I use the kbhit function to make a snake program?
kbhit() is not a standard C library function - I checked, it is Borland-specific. This means if you use it your program will not be portable to other C compilers.





It isn't that hard. kbhit() returns non-zero if a key is waiting in the buffer. So, you need something like the following:





for (;;) {


...if (kbhit()) {


......changeDirection(%26amp;state);


...}


...if (!move(%26amp;state))break;


...delay(%26amp;state);


}





where state is a structure that contains your state information (location, size, speed, score...), move() moves the snake, and delay() waits a short time to control the snake's speed.





In changeDirection() you need to use getchar() or something to read the command, and then update the state structure to reflect the new direction.

garden flowers

No comments:

Post a Comment