Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause a loop in C/C++

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;
}
like image 962
Luis Carlos Castillo Avatar asked Feb 16 '26 08:02

Luis Carlos Castillo


1 Answers

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());
like image 130
Alex Z Avatar answered Feb 17 '26 22:02

Alex Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!