go-chip8/main.go
main.goRaw
1package main
2
3import (
4 "flag"
5 "fmt"
6)
7
8type chip8 struct {
9 opcode uint16
10 memory [4096]byte
11
12 // register
13 v [16]byte
14
15 index uint16
16 pc uint16
17
18 gfx [64 * 32]byte
19
20 delayTimer byte
21 soundTimer byte
22
23 stack [16]uint16
24 sp int
25
26 key [16]byte
27
28 drawFlag bool
29}
30
31// Initialize registers and memory once
32func (c *chip8) initialize() {
33 c.pc = 0x200
34 c.opcode = 0
35 c.index = 0
36 c.sp = 0
37}
38
39func (c *chip8) emulateCycle() {
40 // Fetch Opcode
41 c.opcode = uint16(c.memory[c.pc])<<8 | uint16(c.memory[c.pc+1])
42
43 // Decode Opcode
44 // https://en.wikipedia.org/wiki/CHIP-8#Opcode_table
45 // http://www.multigesture.net/wp-content/uploads/mirror/goldroad/chip8_instruction_set.shtml
46 switch c.opcode & 0xF000 {
47 case 0x0000:
48 switch c.opcode & 0x000F {
49 case 0x0000: // 0x00E0
50 // clear screen
51 // TODO
52 c.pc += 2
53 break
54 case 0x000E: // 0x00EE
55 // TODO
56 break
57 default:
58 fmt.Printf("Unknown opcode [0x0000]: 0x%X\n", c.opcode)
59 }
60 case 0x2000:
61 c.stack[c.sp] = c.pc
62 c.sp++
63 c.pc = c.opcode & 0x0FFF
64 break
65 case 0x6000:
66 pos := (c.opcode & 0x0F00) >> 8
67 c.v[pos] = byte(c.opcode)
68 c.pc += 2
69 break
70 default:
71 fmt.Printf("Unknown opcode: 0x%X\n", c.opcode)
72 }
73
74 // Update timers
75 if c.delayTimer > 0 {
76 c.delayTimer--
77 }
78 if c.soundTimer > 0 {
79 if c.soundTimer == 1 {
80 fmt.Printf("Beep!\n")
81 }
82 c.soundTimer--
83 }
84}
85
86func (c *chip8) loadGame(filepath string) error {
87 return nil
88}
89
90func (c *chip8) drawGraphics() {
91
92}
93
94func (c *chip8) setKeys() {
95
96}
97
98func main() {
99 filepath := flag.String("file", "file-path", "file path of the input file")
100
101 flag.Parse()
102
103 // setupGraphics()
104 // setupInput()
105
106 var c chip8
107 c.initialize()
108 err := c.loadGame(*filepath)
109 if err != nil {
110 panic(err)
111 }
112
113 for {
114 c.emulateCycle()
115 if c.drawFlag {
116 c.drawGraphics()
117 c.setKeys()
118 }
119 }
120}