How to randomly move object to different positions such as drawcircle() each time you run the c++ program. I have been given rushhour gane.so each time i run the c++ program the object is placed at a random position different from the previous position. Can it be done through rand() srand() or arrays. Please guide me how to do it.
#include<dos.h>
#include<conio.h>
void main()
{
int
i=250,j=250,x=0,y=-1,ch,gd=DETECT,gm;
initgraph(&gd,&gm,”c:\turboc3\bgi”);
while(1) //infinite
loop
{
circle(i,j,30);
outtextxy(400,400,”Press
Esc to Exit…..”);
if(kbhit()) //check
if a key is pressed
{
ch=getch();
if(ch==57) //move upward
{
x=0;
y=-1;
}
if(ch==61) //move left
{
x=-1;
y=0;
}
if(ch==63) //move right
{
x=1;
y=0;
}
if(ch==62) //move downward
{
x=0;
y=1;
}
if(ch==27) //exit when esc
pressed
exit(0);
}
i=i+x;
j=j+y;
delay(50);
cleardevice();
}
}
Ok! Let’s understand what is actually happening here.
Initial values of i and j are 250, so that the circle will first
printed at coordinate (250,250) and initial values of x and y are 0 and -1 to
make the circle move upward. We have used an infinite while loop and in that loop
we used a function called kbhit() to
check if any key is pressed or not.
Initially the circle is moving upward, suppose right arrow
key is pressed then 77 (ASCII value of right arrow key) is stored in ch and values of x and y become 1 and 0
respectively. Now value of i
increased by one and j remains as it
is, this make the circle to move by one coordinate in x direction. This process
is repeated again and again till any other arrow key is pressed.
The program exit if escape (ASCII value 27) key is pressed.
Here we have used cleardevice()
function to clear previous printed data and after that circle is printed at new
coordinate which makes circle to appear as if it is moving.
Comments
Leave a comment