adding timer to game

天涯浪子 提交于 2019-12-02 05:38:09

You can use PIT as a timer I used it in here:

its a mines game in old Turbo C++ and MS-DOS. For more info about PIT see:

there are links to PIT reference and examples I recommend you to see the PCGPE.

Now back to your question. You should register PIT ISR routine doing your timing/timeouting in the background ... Here example I just busted in DOSBOX:

#include <dos.h>
#include <conio.h>
#include <iostream.h>

int stop=0;
int timeout_cnt=0;

const int int_PIT=0x08;
void interrupt (*isr_PIT0)(...)=NULL; // original ISR handler
void interrupt isr_PIT(...) // new ISR handler
    {
    isr_PIT0(); // call original handler
    // here do your stuff
    if (timeout_cnt) timeout_cnt--;
    else stop=1;
    }

void main()
    {
    clrscr();
    isr_PIT0=getvect(int_PIT);  // store original ISR
    setvect(int_PIT,isr_PIT);   // set new ISR
    cout << "start counting" << endl;
    stop=0;
    timeout_cnt=(3*182)/10;     // init timeout 18.2Hz -> 3 sec
    for (;!stop;)
        {
        // here do your stuff
        }
    cout << "timeouted" << endl;
    setvect(int_PIT,isr_PIT0);  // restore original ISR
    getch(); // this is duplicated just to avoid DOSBOX glitches
    getch();
    getch();
    }

You basically need just dos.h all the other stuff is just for printing and handling keyboard.

So I created ISR that hooks up to PIT which is called with 18.2 Hz frequency. The timeout is initiated by setting the timeout_cnt to timeout time value and reseting the stop:

stop = 0;
timeout_cnt = time[sec] * 18.2;

ported to integer... once counter underflows it sets the stop value to true. I also call the original ISR handler as MS-DOS relays on it. Do not forget to restore original ISR before apps exit.

btw the timeout_cnt and stop variables should be volatile but IIRC it does not matter in old Turbo C++ as there are no optimizations that could optimize them out to speak of.

In case you change the PIT frequency you should call the original handler with 18.2 Hz and restore original PIT frequency before apps exit.

This can be also used as a sort of multitasking as you can do stuff in the ISR handler too (regardless of the main code) but you need to be careful as the main code can be paused at any time like in middle of writing string to screen and if your background stuff is printing too you can have distorted output etc ... so similar rules like in multi-threading applies.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!