I am trying to learn how to use graphics.h and conio.h libraries.I am developing a graphic program which i need to move a rectangle after keyboard input.ex: if player press right , rectangle should move right side.Problem is i don't know how to get user input.I need to get user input inside a loop continuous.Here is my code.Any help is appreciated(keyword,function name etc)
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
void drawrect(int left,int top,int right,int bot);
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
drawrect(5,400,40,450); // default start position
firsttime=1;//counter for if its first time in for loop
int currentl=5;
int currentt=400;
int currentr=40;
int currentb=450;
if(firsttime==1)
{
//get user input and drawrectangle with new inputs
//if player press right add 5 to currentl and current r and
//redraw the rectangle
}
getch();
closegraph();
}
void drawrect(int left,int top,int right,int bot)
{
rectangle(left,top,right,bot);
}
You can use getch()
or _getch()
to read codes of keys and react on it. But some things you should think over.
1) loop is needed to perform continuois action in your program.
2) keys such as "arrow left", "arrow up", etc. is given by getch()
as two codes - the first -32 and the second depends on key.
Use the following programm to see the loop example and to find codes for keys:
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
char ch;
printf("Press 'q' to exit prom program\n");
do{
ch = _getch();
printf("%c (%d)\n", ch, ch);
} while( ch != 'q');
}