I made a chip8 emulator, but ran into some problems with detecting collision when drawing. Chip8 draws onto the screen by XOR'ing individual pixels onto the screen, and setting a flag if a pixel is turned off. My code is as follows:
_DXYN: function(X, Y, N) {
console.log("_DXYN");
for (var i = 0; i < N; i++) {
for (var j = 0; j < 8; j++) {
var bitBefore = graphics[(i + cpu.registers.V[Y]) * 64 + j + cpu.registers.V[X]];
var bitAfter = bitBefore ^ cpu.getBits(memory[cpu.registers.I + i])[j];
graphics[(i + cpu.registers.V[Y]) * 64 + j + cpu.registers.V[X]] = bitAfter;
if ((bitBefore != bitAfter) && bitBefore == 1)
cpu.registers.V[0xF] = 0x1;
else
cpu.registers.V[0xF] = 0x0;
}
}
}
graphics
is a 1-dimensional array of ints, each corresponding to a pixel on the screen. A pixel is on if its corresponding integer in the array is a 1, and off it it is a 0. The cpu
object contains all the methods, including this one, as well as the registers. X
is the opcode parameter for the register which contains the x coordinate of the sprite to draw, and Y
is the opcode parameter for the register with the y coordinate. The I
register is the location in memory to read from. The cpu.getBits
function is as follows:
getBits: function(opcode) {
var bits = [];
for (var i = 0; i < 8; i++) {
bits.push((opcode >> i) & 1)
}
return bits.reverse();
}
The complete code can be found on github here: https://github.com/ichub/Chip8 Look in chip8cpu.js for the implementation.