-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chip8.js
121 lines (96 loc) · 3.16 KB
/
Chip8.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
(() => {
const V_MEM_SIZE = 64 * 32
const fontSet = new Uint8Array(
[
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
]
)
class Chip8 extends chip8.lib.EventEmitter {
constructor() {
super()
this.reset()
this.reset = this.reset.bind(this)
this.load = this.load.bind(this)
this.step = this.step.bind(this)
this.execute = this.execute.bind(this)
}
reset() {
this.memory = new Uint8Array(4096)
this.kMemory = new Uint8Array(16);
this.vMemory = new Uint8Array(V_MEM_SIZE)
this.pc = new chip8.Pc()
this.v = new Uint8Array(16)
this.i = 0
this.stack = new Array()
this.delayTimer = 0
this.soundTimer = 0
fontSet.forEach((chunk, i) => {
this.memory[i] = chunk
})
}
load(program) {
this.reset()
program.forEach((byte, index) => {
this.memory[this.pc.startAddr + index] = byte
})
}
step() {
for (let i = 0; i < 10; i++) {
const hiByte = this.memory[this.pc.addr]
const loByte = this.memory[this.pc.addr + 1]
const opcode = new chip8.Opcode(hiByte, loByte)
this.execute(opcode)
}
this.updateTimers()
}
updateTimers() {
if (this.delayTimer > 0) {
this.delayTimer -= 1
}
if (this.soundTimer > 0) {
this.soundTimer -= 1
}
}
execute(opcode) {
this.pc.next()
const result = chip8.executors.get(opcode.nibbles[0])(opcode, this)
this.emit('debug', { opName: opcode.toHex() })
if (opcode.isDraw()) {
this.emit('draw', { payload: result })
}
if (opcode.isClear()) {
this.emit('clear')
}
if (opcode.isWait()) {
this.emit('wait', { payload: result })
}
if (this.soundTimer > 0) {
this.emit('beepRun')
} else {
this.emit('beepStop')
}
}
setKey(key) {
this.kMemory[key] = 1
}
unsetKey(key) {
this.kMemory[key] = 0
}
}
window.chip8.Chip8 = Chip8
})()