Jun 12, 2007

C++ program to controle an object through keyboard

// C++ program to draw a circle on the screen and controlling it
// through keyboard by direction keys.

#include<iostream.h>
#include<conio.h>
#include<dos.h>
#include<graphics.h>
#include<stdlib.h>
class snake{
int x,y;
int randx,randy;
public :
int success;
snake()
{
int dv,mo;
x=320;y=240;
success=0;
dv = DETECT;
initgraph(&dv,&mo,"");
circle(x,y,4);
randomize();
nextPoint();
}


~snake(){
getch();
closegraph();}
moveUp()
{cleardevice();
y -= 1;
circle(x,y,4);
if (x==randx & y==randy)
{randx=1+random(639);
randy=1+random(479);}
nextPoint();}
moveLeft(){
cleardevice();
x -= 1;
circle(x,y,4);
if (x==randx & y==randy)
{
randx=1+rand()%639;
randy=1+rand()%479;
}
nextPoint();
}

moveRight()
{
cleardevice();
x += 1;
circle(x,y,4);
if (x==randx & y==randy)
{
randx=1+random(639);
randy=1+random(479);}
nextPoint();}
moveDown()
{
cleardevice();
y += 1;
circle(x,y,4);
if (x==randx & y==randy)
{
randx=1+random(639);
randy=1+random(479);}
nextPoint();
}

nextPoint()
{
circle(randx,randy,1);}
};

//snake dj(5);
snake dj;
main()
{
while(!0)
{
int tch=getch();
int ch=getch();
cout <<tch<<" "<< ch;
if (ch==72) dj.moveUp();
if (ch==75) dj.moveLeft();
if (ch==77) dj.moveRight();
if (ch==80) dj.moveDown();
}
}

No comments:

Post a Comment