我打算写一个nes模拟器。但首先,要了解仿真的工作原理,我将编写一个 Chip-8 仿真器。
模拟器快完成了。我在游戏中有一些错误,但很快就会修复。我的问题 1 是将仿真器与 Chip-8 的时钟速度同步。在我经常阅读的互联网上,一般时钟速度应该是〜540Hz。芯片的定时器应以 60Hz 的频率计时。
为了使我的模拟器与 Chip-8 同步,我编写了以下逻辑:
private void GameTick()
{
Stopwatch watch = new Stopwatch();
var instructionCount = 0;
_gameIsRunning = true;
while (_gameIsRunning)
{
watch.Restart();
EmulateCycle();
//Updates the internal timer at a 60hz frequenz
//540hz (game tick) divided by 9 equals 60hz (timer tick)
instructionCount++;
if(instructionCount == 9)
{
UpdateSoundAndDelay();
instructionCount = 0;
}
if (_readyToDraw)
{
DrawGraphics();
_readyToDraw = false;
}
SetKeys();
//Pause the game to get a virtual clock speed of ca. 540mhz
var elapsedMicroseconds = watch.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
while(elapsedMicroseconds < 1852)
{
elapsedMicroseconds = watch.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
}
}
}
有关更多详细信息,请查看我的仓库:https ://github.com/Marcel-Hoffmann/Chip-8-Emulator
如您所见,对于每个 cpu 周期,我将等待 1852 微秒。结果将是每秒约 540 个周期,等于 540Hz。但我对这个逻辑不是很满意。
有人有更好的想法,如何同步时钟速度?