Tuesday, July 28, 2009

How do you do this in C programming?

how do you make the cursor or an char move with the press of the arrow keys. Example when the program is running how do i make the letter "f" move up and down,left and right,and diagonally in the screen??And another what is the syntax for function random??

How do you do this in C programming?
For cursor movement, you'll need 2 functions. One of them is an input function(s) which doesn't wait around for user input (like the scanf() function). The other function is one which moves the cursor.





The kbhit() and getch() functions can get the keyboard input for you (they are defined in conio.h). The kbhit() function checks to see if a key was pressed (it doesn't pause), and the getch() function can return the ASCII code of the key that was pressed. If your program doesn't have to do something else while you're waiting for a key press, then you can use the getch() function without kbhit(). For non-printing keys, getch() returns 0xFFE0. You then have to call getch() again to get the other byte of the keycode.





Example:


// program code


if (kbhit())


{


key=getch();


if (key==0xFFE0) // non-printing key?


{


key=getch(); // get second part of key #


}


}


// continue code





Cursor placement can be accomplished by using the gotoxy() function (also defined in conio.h). Outputting a character can be done with putch().





The rand() function creates an unsigned integer. For 16 bit compilers, rand() returns a signed integer from -32768 to 32767.


(You can modify the call to rand() so that it returns the numbers in the range that you want.) Near the start of your program, you should call the srand() function. This function 'seeds' the rand() function. If you don't do this, then your program will always come up with the same 'random' numbers.





Example:


#include %26lt;stdlib.h%26gt;


#include %26lt;time.h%26gt;


time_t t;


int num;





int main(void)


{


srand((unsigned) time(%26amp;t)); // seed random number generator





// Random number between +1300 and +1400:


num=(1300+rand()%1400);


// Random number between +200 to + 2000, in multiples of 10:


num=((200+(rand() % 180)*10));


// Random number between +1 to +50:


num=(1+rand() % 50);


return 0;


}


No comments:

Post a Comment