I'm writing a CHIP-8 emulator in C++, which has two timers. If these timers are non-zero, they are decremented by 1 at 60Hz. I'm still getting the hang of C++, so I wanted to see if I'm doing this the Right Way.
Here's the header file:
#include <chrono>
struct TimedRegister
{
unsigned char value;
std::chrono::time_point<std::chrono::high_resolution_clock> last_write;
TimedRegister();
void set(const unsigned char new_value);
void decrement();
};
And this is the the implementation:
#include "chip8.hpp"
#include <chrono>
TimedRegister::TimedRegister()
: value(0)
{}
void
TimedRegister::set(const unsigned char new_value)
{
value = new_value;
last_write = std::chrono::high_resolution_clock::now();
}
void
TimedRegister::decrement()
{
if (value == 0)
return;
const auto now = std::chrono::high_resolution_clock::now();
if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_write)
.count() >= 1000 / 60) {
--value;
last_write = now;
}
}
The decrement function is called from the main emulator loop like this:
while (!chip8.halted) {
chip8.delay_timer.decrement();
}
They seem to work fine, but I'm not sure if I'm getting away with using a heavy-handed, brute-force approach.