a loop is not good for delay. E.G if the function delays 5 seconds with your
processor, a faster computer will make the function to delay 2 seconds while
a slower one will make the function to delay 10 seconds. and so on. anyway,
here is a working alternative which delays the same no matter how much
fast your Pc is:
Code:
/* Load Libraries */
#include <conio.h>
#include <windows.h>
#include <stdio.h>
#include <time.h>
/* Load also Stdlib.h because it has the sleep function */
#include <stdlib.h>
/* Declare Goto Function */
void gotoxy(int, int);
/* Init X and Y plus the Variables which hold
previous X and Y. */
int x, y, lastx, lasty;
/* Make a CHAR variable to get Key Input */
char a;
/* Main Function */
int main()
{
/* type some message for the user */
printf("My Moving Char program!\n\n");
/* sleep waits in miliseconds, so 5 * 1000 = 5 seconds */
sleep(5 * 1000);
/* Clear the screen completely */
system("cls");
/* if we dont use SRAND, RAND returns the same number over and over */
srand((unsigned) time(NULL));
/* a typical Console screen is 80x40, since a Console Screen is
made of only text. 80 is the number of columns and 40 is the
number of rows. so we randomize X and Y in those areas */
x = (rand() % 80) + 1; y = (rand() % 40) + 1;
/* Store the previous X and Y */
lastx = x; lasty = y;
/* start an Infinite Loop */
while(1 == 1)
{
/* Head to LastX and LastY and clear old O*/
gotoxy(lastx, lasty);
printf(" ");
/* Draw New O */
gotoxy(x,y);
printf("O");
/* Get Input */
a = getch();
/* Remember Old X and Y */
lastx = x; lasty = y;
/* If Down Arrow is Pressed, Y is increased */
if (a == 80) y = y + 1;
/* If Up Arrow is Pressed, Y is decreased */
if (a == 72) y = y - 1;
/* If Right Arrow is Pressed, X is increased */
if (a == 77) x = x + 1;
/* If Left Arrow is Pressed, X is decreased */
if (a == 75) x = x - 1;
}
}
/* Make GOTOXY function */
void gotoxy(int eex, int eey)
{
COORD coord;
coord.X = eex;
coord.Y = eey;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}