-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfull-chip.py.bak
365 lines (339 loc) · 13.7 KB
/
full-chip.py.bak
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import pygame, re, sys, random
import pygame.locals as plocals
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
print("Usage: %s [filename]" % sys.argv[0])
sys.exit(1)
ON_COLOR = (205,205,205)
OFF_COLOR = (50,50,50)
PIX_SIZE = 20
TPF = 50 # Ticks per Frame
FPS = 60 # Frames per Second
KEYMAP = {
plocals.K_1: 0x1, plocals.K_2: 0x2, plocals.K_3: 0x3, plocals.K_4: 0xC,
plocals.K_q: 0x4, plocals.K_w: 0x5, plocals.K_e: 0x6, plocals.K_r: 0xD,
plocals.K_a: 0x7, plocals.K_s: 0x8, plocals.K_d: 0x9, plocals.K_f: 0xE,
plocals.K_z: 0xA, plocals.K_x: 0x0, plocals.K_c: 0xB, plocals.K_v: 0xF,
plocals.K_SPACE: 0x6,
plocals.K_UP: 0x5,
plocals.K_LEFT: 0x7, plocals.K_DOWN: 0x8, plocals.K_RIGHT: 0x9,
}
pygame.mixer.init(44100, -16, 1, 512)
pygame.init()
win = pygame.display.set_mode((64*PIX_SIZE,32*PIX_SIZE))
pygame.display.set_caption("CHIP-8")
#4x5 hex fontset
fontset = bytes([
# 0
0xF0, 0x90, 0x90, 0x90, 0xF0,
# 1
0x10, 0x10, 0x10, 0x10, 0x10,
# 2
0xF0, 0x10, 0xF0, 0x80, 0xF0,
# 3
0xF0, 0x10, 0xF0, 0x10, 0xF0,
# 4
0x90, 0x90, 0xF0, 0x10, 0x10,
# 5
0xF0, 0x80, 0xF0, 0x10, 0xF0,
# 6
0xF0, 0x80, 0xF0, 0x90, 0xF0,
# 7
0xF0, 0x10, 0x10, 0x10, 0x10,
# 8
0xF0, 0x90, 0xF0, 0x90, 0xF0,
# 9
0xF0, 0x90, 0xF0, 0x10, 0xF0,
# A
0xF0, 0x90, 0xF0, 0x90, 0x90,
# B
0xE0, 0x90, 0xE0, 0x90, 0xE0,
# C
0xF0, 0x80, 0x80, 0x80, 0xF0,
# D
0xE0, 0x90, 0x90, 0x90, 0xE0,
# E
0xF0, 0x80, 0xF0, 0x80, 0xF0,
# F
0xF0, 0x80, 0xF0, 0x80, 0x80
])
class CHIP8Error(Exception):
pass
class CHIP8:
def __init__(self, cartdata=bytes()):
self.memory = bytearray(4096)
self.V = bytearray(16)
self.I = 0
self.pc = 512
self.gfx = bytearray(64*32)
self.delay_timer = 0
self.sound_timer = 0
self.keys = bytearray(16)
self.drawFlag = False
self.stack = []
self.keypress_tmp = set()
for i in range(len(fontset)):
self.memory[i + 80] = fontset[i]
for i in range(len(cartdata)):
self.memory[i + 512] = cartdata[i]
def cycle(self, delta):
# Get Opcode
opcode = self.memory[self.pc] << 8 | self.memory[self.pc + 1]
ophex = "{:0>4}".format(hex(opcode)[2:]).upper()
# Decode and Execute Opcode
if ophex == "00E0":
# 00E0: Clear screen
self.gfx = bytearray(64*32)
self.drawFlag = True
elif ophex == "00EE":
# 00EE: Return from subroutine
if len(self.stack) == 0:
raise CHIP8Error(f"Return at {hex(self.pc)} has nowhere to go")
self.pc = self.stack.pop() - 2
elif re.fullmatch("1...", ophex):
# 1xxx: Jump to [nnn]
self.pc = int(ophex[1:],16) - 2
elif re.fullmatch("2...", ophex):
# 2nnn: Call subroutine at [nnn]
if len(self.stack) == 16:
raise CHIP8Error(f"Stack is full, cannot call subroutine")
self.stack.append(self.pc + 2)
self.pc = int(ophex[1:],16) - 2
elif re.fullmatch("3...", ophex):
# 3xnn: Skips next instruction if V[x] equals [nn]
if self.V[int(ophex[1],16)] == int(ophex[2:],16):
self.pc += 2
elif re.fullmatch("4...", ophex):
# 4xnn: Skips next instruction if V[x] doesn't equal [nn]
if self.V[int(ophex[1],16)] != int(ophex[2:],16):
self.pc += 2
elif re.fullmatch("5..0", ophex):
# 5xy0: Skips next instruction if V[x] equals V[y]
if self.V[int(ophex[1],16)] == self.V[int(ophex[2],16)]:
self.pc += 2
elif re.fullmatch("6...", ophex):
# 6xnn: Set V[x] to [nn]
self.V[int(ophex[1],16)] = int(ophex[2:],16)
elif re.fullmatch("7...", ophex):
# 7xnn: Add [nn] to V[x]
self.V[int(ophex[1],16)] = (
self.V[int(ophex[1],16)] + int(ophex[2:],16)
) % 256
elif re.fullmatch("8..0", ophex):
# 8xy0: Set V[x] to V[y]
self.V[int(ophex[1],16)] = self.V[int(ophex[2],16)]
elif re.fullmatch("8..1", ophex):
# 8xy1: Set V[x] to V[x] OR V[y]
self.V[int(ophex[1],16)] |= self.V[int(ophex[2],16)]
elif re.fullmatch("8..2", ophex):
# 8xy2: Set V[x] to V[x] AND V[y]
self.V[int(ophex[1],16)] &= self.V[int(ophex[2],16)]
elif re.fullmatch("8..3", ophex):
# 8xy3: Set V[x] to V[x] XOR V[y]
self.V[int(ophex[1],16)] ^= self.V[int(ophex[2],16)]
elif re.fullmatch("8..4", ophex):
# 8xy4: Add V[y] to V[x], and set Vf to whether there was an
# overflow or not
total = self.V[int(ophex[1],16)] + self.V[int(ophex[2],16)]
self.V[int(ophex[1],16)] = total % 256
self.V[15] = total > 256
elif re.fullmatch("8..5", ophex):
# 8xy7: Subtract V[y] from V[x], and set Vf to whether there was
# a borrow or not
total = self.V[int(ophex[1],16)] - self.V[int(ophex[2],16)]
self.V[int(ophex[1],16)] = total % 256
self.V[15] = total >= 0
elif re.fullmatch("8..6", ophex):
# 8xy6: Shifts V[y] to the right by 1, putting the underflowflow
# in Vf, and putting the result in V[x]
self.V[15] = self.V[int(ophex[2],16)] & 1
self.V[int(ophex[1],16)] = (self.V[int(ophex[2],16)]>>1)%256
elif re.fullmatch("8..7", ophex):
# 8xy7: Subtract V[y] from V[x], and set Vf to whether there was
# a borrow or not
total = self.V[int(ophex[2],16)] - self.V[int(ophex[1],16)]
self.V[int(ophex[1],16)] = total % 256
self.V[15] = total >= 0
elif re.fullmatch("8..E", ophex):
# 8xyE: Shifts V[y] to the left by 1, putting the overflow in Vf,
# and putting the result in V[x]
self.V[15] = self.V[int(ophex[2],16)]//128
self.V[int(ophex[1],16)] = (self.V[int(ophex[2],16)]<<1)%256
elif re.fullmatch("9..0", ophex):
# 9xy0: Skips next instruction if V[x] doesn't equal V[y]
if self.V[int(ophex[1],16)] != self.V[int(ophex[2],16)]:
self.pc += 2
elif re.fullmatch("A...", ophex):
# Annn: Set I to [nnn]
self.I = int(ophex[1:],16)
elif re.fullmatch("B...", ophex):
# Bnnn: Jump to [nnn] plus V0
self.pc = int(ophex[1:],16) + self.V[0] - 2
elif re.fullmatch("C...", ophex):
# Cxnn: Set V[x] to a random number, and bitwise-AND it with [nn]
self.V[int(ophex[1],16)] = random.randint(0, 255) & int(ophex[2:],16)
elif re.fullmatch("D...", ophex):
# Dxyn: XOR sprite stored at the I pointer with height [n] at [x], [y] onto display
flipped_on = False
x, y = self.V[int(ophex[1],16)], self.V[int(ophex[2],16)]
for sy in range(int(ophex[3],16)):
for sx in range(8):
sprite_index = self.I + sy
if not self.memory[sprite_index] & (128 >> sx):
continue
gfx_index = ((x+sx)%64) + (((y+sy)%32)*64)
if self.gfx[gfx_index]:
flipped_on = True
self.gfx[gfx_index] ^= 1
self.V[15] = int(flipped_on)
self.drawFlag = True
elif re.fullmatch("E.9E", ophex):
# ExA1: Skips next instruction if the key V[x] is pressed
if self.V[int(ophex[1],16)] < 16 and self.keys[self.V[int(ophex[1],16)]]:
self.pc += 2
elif re.fullmatch("E.A1", ophex):
# ExA1: Skips next instruction if the key V[x] is not pressed
if self.V[int(ophex[1],16)] > 15 or not self.keys[self.V[int(ophex[1],16)]]:
self.pc += 2
elif re.fullmatch("F.07", ophex):
# Fx07: Set V[x] to delay timer
self.V[int(ophex[1],16)] = int(self.delay_timer)
elif re.fullmatch("F.15", ophex):
# Fx15: Set delay timer to V[x]
self.delay_timer = self.V[int(ophex[1],16)]
elif re.fullmatch("F.18", ophex):
# Fx15: Set sound timer to V[x]
self.sound_timer = self.V[int(ophex[1],16)]
elif re.fullmatch("F.0A", ophex):
# Fx0A: Await key press and release and store in V[x]
success = False
for i in range(16):
if self.keys[i]:
self.keypress_tmp.add(i)
to_remove = []
for i in self.keypress_tmp:
if not self.keys[i]:
self.V[int(ophex[1],16)] = i
success = True
to_remove.append(i)
for i in to_remove:
self.keypress_tmp.remove(i)
if not success:
self.pc -= 2
elif re.fullmatch("F.1E", ophex):
# Fx1E: Add V[x] to I, and set Vf to whether there was an overflow or not
total = self.I + self.V[int(ophex[1],16)]
self.I = total % 0x1000
self.V[15] = total > 0xFFF
elif re.fullmatch("F.29", ophex):
# Fx29: Set I to the fontset index of the value of V[x]
self.I = 0x50 + (len(fontset) // 16) * (
self.V[int(ophex[1],16)]%16
)
elif re.fullmatch("F.33", ophex):
# Fx33: Dump the 3-digit decimal representation of V[x] into
# memory, starting at I
dec = "{:>03}".format(self.V[int(ophex[1],16)])
for i in range(3):
self.memory[self.I + i] = int(dec[i])
elif re.fullmatch("F.55", ophex):
# Fx55: Dump V0..V[x] into memory, starting at I
for i in range(int(ophex[1],16)+1):
self.memory[self.I + i] = self.V[i]
elif re.fullmatch("F.65", ophex):
# Fx65: Load memory into V0..V[x], starting at I
for i in range(int(ophex[1],16)+1):
self.V[i] = self.memory[self.I + i]
else:
raise CHIP8Error(f"Unknown OpCode at {hex(self.pc)}: 0x{ophex}")
self.pc += 2
# Update timers
self.delay_timer = max(0, self.delay_timer - (delta * 60))
self.sound_timer = max(0, self.sound_timer - (delta * 60))
def printmem(chip):
for i in range(0, 4096, 16):
tmp = ""
for j in chip.memory[i:i+(16)]:
tmp += hex(j) + "\t"
print(tmp)
putchars = (
b"\x62\x00\x61\x00\x63\x00\x60\x05\xA2\x20\xD1\x25\x71\x05\x73\x05"
b"\xF0\x1E\x33\x28\x12\x1A\x62\x06\x61\x00\x33\x50\x12\x0A\x12\x1E"
b"\xF0\x90\x90\x90\xF0\x10\x10\x10\x10\x10\xF0\x10\xF0\x80\xF0\xF0"
b"\x10\xF0\x10\xF0\x90\x90\xF0\x10\x10\xF0\x80\xF0\x10\xF0\xF0\x80"
b"\xF0\x90\xF0\xF0\x10\x10\x10\x10\xF0\x90\xF0\x90\xF0\xF0\x90\xF0"
b"\x10\xF0\xF0\x90\xF0\x90\x90\xE0\x90\xE0\x90\xE0\xF0\x80\x80\x80"
b"\xF0\xE0\x90\x90\x90\xE0\xF0\x80\xF0\x80\xF0\xF0\x80\xF0\x80\x80"
)
tank = (
b"\x61\x20\x62\x10\xA2\x1E\xD1\x27\xF0\x0A\xD1\x27\x40\x05\x22\x38"
b"\x40\x07\x22\x44\x40\x09\x22\x4A\x40\x08\x22\x3E\x12\x06\x10\x54"
b"\x7C\x6C\x7C\x7C\x44\x7C\x7C\x6C\x7C\x54\x10\x00\xFC\x78\x6E\x78"
b"\xFC\x00\x3F\x1E\x76\x1E\x3F\x00\x72\xFF\xA2\x1E\x00\xEE\x72\x01"
b"\xA2\x24\x00\xEE\x71\xFF\xA2\x31\x00\xEE\x71\x01\xA2\x2B\x00\xEE"
)
mondri8 = (
b"\xA2\x72\x66\x0A\x22\x24\x22\x4E\x22\x24\x22\x3A\x76\xFF\x36\x00"
b"\x12\x04\x66\x05\x22\x24\x22\x62\x76\xFF\x36\x00\x12\x14\xF0\x0A"
b"\x00\xE0\x12\x02\xC0\xFF\xC1\xFF\x00\xEE\xD2\x31\x3F\x00\x12\x36"
b"\x82\x44\x83\x54\x12\x2A\xD2\x31\x00\xEE\x82\x00\x64\x00\x83\x10"
b"\x65\xFF\x22\x2A\x83\x10\x65\x01\x83\x54\x22\x2A\x00\xEE\x83\x10"
b"\x65\x00\x82\x00\x64\xFF\x22\x2A\x82\x00\x64\x01\x82\x44\x22\x2A"
b"\x00\xEE\x22\x4E\x71\x01\xD0\x11\x3F\x00\x12\x6E\x12\x62\xD0\x11"
b"\x00\xEE\x80"
)
def draw(chip, win):
for i in range(64*32):
pix_rect = (
i%64*PIX_SIZE, i//64*PIX_SIZE,
PIX_SIZE, PIX_SIZE
)
if chip.gfx[i]:
pygame.draw.rect(win, ON_COLOR, pix_rect)
else:
pygame.draw.rect(win, OFF_COLOR, pix_rect)
pygame.display.update()
def loadfile(filename):
f = open(filename, "rb")
return f.read()
c = CHIP8(loadfile(filename)) #bytes([0x60, 0x01, 0x61, 0x01, 0x60, 0x00, 0x61, 0x00, 0x12, 0x00]))
# For IDLE autocomplete
self = c
draw(c, win)
clock = pygame.time.Clock()
buzz = pygame.mixer.Sound("buzzer.wav")
buzz_playing = False
try:
while True:
for _ in range(TPF-1):
c.cycle(0)
#opcode = c.memory[c.pc] << 8 | c.memory[c.pc + 1]
#print("Registers: %s" % " ".join([str(i) for i in c.V]))
#input(f"I: {hex(c.I)}\tPC: {hex(c.pc)}\tOphex: {hex(opcode)}")
c.cycle(clock.tick(FPS)/1000)
if c.drawFlag:
c.drawFlag = False
draw(c, win)
if buzz_playing != (c.sound_timer >= 1):
if buzz_playing:
buzz.stop()
else:
buzz.play(-1)
buzz_playing = not buzz_playing
buzz.set_volume(int(c.sound_timer>=1))
for event in pygame.event.get():
if event.type == 2: #Key down
if event.key in KEYMAP:
c.keys[KEYMAP[event.key]] = 1
if event.type == 3: #Key up
if event.key in KEYMAP:
c.keys[KEYMAP[event.key]] = 0
if event.type == 12: #Quit
raise KeyboardInterrupt()
except CHIP8Error as e:
sys.stderr.write("CHIP-8 Error: " + str(e) + "\n")
pygame.quit()
except KeyboardInterrupt:
print("Goodbye!")
pygame.quit()