Question

I am trying to make a screen for a car game and make the screen wait for a key to go into the next screen, thing is that with this code it changes colors too fast. I've already tried delay() and sleep() which haven't worked properly. Also, after hitting a key, it closes and doesn't wait for me to enter a key. I just want the title to blink between white and red until a key is hit, and get to know why it exits after hitting a key.

Here is my code:

#include <dos.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
    int gdriver = DETECT, gmode, errorcode;
    initgraph(&gdriver, &gmode, "C|\\BORLANDC\\BGI");
    outtextxy(250,280,"POINTER DRIVER 1.0");
    outtextxy(250,290,"LCCM 10070249");
    do
    {
        setcolor(WHITE);
        outtextxy(250,380,"PRESS ANY KEY TO CONTINUE");
        // delay(10); nothing works here :(
        setcolor(RED);
        outtextxy(250,380,"PRESS ANY KEY TO CONTINUE");
    } while(!kbhit());
    cleardevice();
    outtextxy(250,290,"HELLO"); //here it draws mega fast and then exits
    getch();
    closegraph();
    return 0;
}
Was it helpful?

Solution

Instead of using delay(10), maybe try using some sort of timer variable to do this. Try something like the following (a modification of your do-while loop):

unsigned flashTimer = 0;
unsigned flashInterval = 30; // Change this to vary flash speed
do
{
    if ( flashTimer > flashInterval )
        setcolor(RED);
    else
        setcolor(WHITE);

    outtextxy(250,380,"PRESS ANY KEY TO CONTINUE");

    ++flashTimer;
    if ( flashTimer > flashInterval * 2 )
        flashTimer = 0;

    // Remember to employ any required screen-sync routine here
} while(!kbhit());

OTHER TIPS

kbhit() returns true if there's a character in the buffer, but doesn't remove the character before it returns. Once you reach the getch() line, it takes the first key that you pressed to break out of the while loop.

Possible solution: While it's a bit hacky, adding a getch() right after your while loop would probably fix it.

May I also suggest using ncurses instead of those Borland libraries?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top