├── .gitattributes
├── .gitignore
├── Chip8.sln
└── Chip8
├── Audio.cs
├── Chip8.csproj
├── Cpu.cs
├── Display.cs
├── Machine.cs
├── Memory.cs
└── Program.cs
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
262 | /Chip8/Settings.StyleCop
263 | /Chip8/IBM.ch8
264 | /Chip8/SI.ch8
265 | /Chip8/test_opcode.ch8
266 |
--------------------------------------------------------------------------------
/Chip8.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30330.147
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Chip8", "Chip8\Chip8.csproj", "{81C54BBE-54A7-4973-A13D-4ADE54D0AD78}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Debug|x64 = Debug|x64
12 | Debug|x86 = Debug|x86
13 | Release|Any CPU = Release|Any CPU
14 | Release|x64 = Release|x64
15 | Release|x86 = Release|x86
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Debug|x64.ActiveCfg = Debug|Any CPU
21 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Debug|x64.Build.0 = Debug|Any CPU
22 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Debug|x86.ActiveCfg = Debug|Any CPU
23 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Debug|x86.Build.0 = Debug|Any CPU
24 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Release|x64.ActiveCfg = Release|Any CPU
27 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Release|x64.Build.0 = Release|Any CPU
28 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Release|x86.ActiveCfg = Release|Any CPU
29 | {81C54BBE-54A7-4973-A13D-4ADE54D0AD78}.Release|x86.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {0FE85290-95ED-42DE-A73E-71F4F1C8384B}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Chip8/Audio.cs:
--------------------------------------------------------------------------------
1 | using SFML.Audio;
2 |
3 | namespace Chip8;
4 |
5 | public class Audio
6 | {
7 | private readonly short[] raw;
8 | private readonly SoundBuffer buffer;
9 | private readonly Sound sound;
10 |
11 | public Audio()
12 | {
13 | raw = new short[44100];
14 |
15 | // Generate square wave for beep
16 | for (uint i = 0; i < 44100; i++)
17 | {
18 | raw[i] = (short)((i / (44100 / 512) / 2 % 2) == 0 ? -10000 : 10000);
19 | }
20 |
21 | buffer = new SoundBuffer(raw, 1, 44100);
22 | sound = new Sound(buffer);
23 | }
24 |
25 | public void Play()
26 | {
27 | sound.Play();
28 | }
29 |
30 | public void Stop()
31 | {
32 | sound.Stop();
33 | }
34 | }
--------------------------------------------------------------------------------
/Chip8/Chip8.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | PreserveNewest
15 |
16 |
17 | PreserveNewest
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/Chip8/Cpu.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Timers;
4 |
5 | namespace Chip8;
6 |
7 | public class Cpu
8 | {
9 | private readonly Memory ram;
10 | private readonly Stack stack;
11 | private readonly Display display;
12 | private readonly Audio beep;
13 | private readonly Random rnd;
14 | private readonly Timer delayTimer;
15 | private readonly bool[] keysPressed;
16 |
17 | // Registers
18 | private readonly byte[] v; // registers V0 to V15
19 | private byte dt; // Delay timer
20 | private byte st; // Sound Timer
21 | private ushort i; // Address register
22 | private ushort pc; // Program Counter
23 |
24 | private bool halted;
25 |
26 | public bool CanDrawSprite;
27 |
28 | public Cpu(Display display, Memory ram, Audio audio, bool[] keysPressed)
29 | {
30 | v = new byte[16];
31 | stack = new Stack();
32 | pc = 0x200;
33 | dt = 0;
34 | st = 0;
35 |
36 | this.display = display;
37 | this.ram = ram;
38 | this.keysPressed = keysPressed;
39 | beep = audio;
40 |
41 | delayTimer = new Timer(16.67);
42 | delayTimer.Elapsed += (s, e) =>
43 | {
44 | if (dt > 0)
45 | {
46 | dt--;
47 | }
48 |
49 | if (st > 0)
50 | {
51 | beep.Play();
52 | st--;
53 | }
54 | else
55 | {
56 | beep.Stop();
57 | }
58 | };
59 | delayTimer.AutoReset = true;
60 | delayTimer.Enabled = true;
61 |
62 | rnd = new Random();
63 | }
64 |
65 | public void Decode()
66 | {
67 | byte opcode = ram.Ram[pc];
68 | int param = opcode & 0xf;
69 | byte data = ram.Ram[pc + 1];
70 |
71 | // Helpers for when using Vx and Vy to make them easier to read
72 | byte x = (byte)param;
73 | byte y = (byte)((data >> 4) & 0xf);
74 |
75 | Console.SetCursorPosition(0, 0);
76 | Console.WriteLine("PC = {0:X4}", pc);
77 |
78 | pc += 2;
79 |
80 | switch (opcode >> 4)
81 | {
82 | case 0x0:
83 | switch (data)
84 | {
85 | case 0xe0: // CLS
86 | display.Clear();
87 | break;
88 |
89 | case 0xee: // RET
90 | if (stack.Count > 0)
91 | {
92 | pc = stack.Pop();
93 | }
94 | break;
95 | }
96 | break;
97 |
98 | case 0x1: // JP nnn
99 | pc = (ushort)((param * 256) + data);
100 | break;
101 |
102 | case 0x2: // CALL nnn
103 | if (stack.Count < 15)
104 | {
105 | stack.Push(pc);
106 | pc = (ushort)((param * 256) + data);
107 | }
108 | break;
109 |
110 | case 0x3: // SE Vx, byte
111 | if (v[x] == data)
112 | {
113 | pc += 2; // skip next instruction if equal
114 | }
115 | break;
116 |
117 | case 0x4: // SNE Vx, byte
118 | if (v[x] != data)
119 | {
120 | pc += 2; // skip next instruction if not equal
121 | }
122 | break;
123 |
124 | case 0x5: // SE Vx, Vy
125 | if (v[x] == v[y])
126 | {
127 | pc += 2; // skip next instruction if equal
128 | }
129 | break;
130 |
131 | case 0x6: // LD Vx, byte
132 | v[x] = data;
133 | break;
134 |
135 | case 0x7: // ADD Vx, byte
136 | v[x] += data;
137 | break;
138 |
139 | case 0x8: // Maths ops
140 | byte flag;
141 | int result;
142 |
143 | switch (data & 0xf)
144 | {
145 | case 0x0: // LD Vx, Vy
146 | v[x] = v[y];
147 | break;
148 |
149 | case 0x1: // OR Vx, Vy
150 | v[x] |= v[y];
151 | v[0x0f] = 0;
152 | break;
153 |
154 | case 0x2: // AND Vx, Vy
155 | v[x] &= v[y];
156 | v[0x0f] = 0;
157 | break;
158 |
159 | case 0x3: // XOR Vx, Vy
160 | v[x] ^= v[y];
161 | v[0x0f] = 0;
162 | break;
163 |
164 | case 0x4: // ADC Vx, Vy
165 | result = v[x] + v[y];
166 | v[x] = (byte)result;
167 | // If result is over 255, we overflowed, so set carry flag, otherwise clear it
168 | v[0xf] = (byte)(result > 255 ? 1 : 0);
169 | break;
170 |
171 | case 0x5: // SBC Vx, Vy
172 | // If Vx is more or equal Vy, we can't overflow, so set carry flag, otherwise clear it
173 | flag = (byte)(v[x] >= v[y] ? 1 : 0);
174 | v[x] -= v[y];
175 | v[0xf] = flag;
176 | break;
177 |
178 | case 0x6: // SHR Vx
179 | //v[x] = v[y];
180 | result = v[x] & 1;
181 | v[x] >>= 1;
182 | v[0xf] = (byte)result;
183 | break;
184 |
185 | case 0x7: // SUBN Vx, Vy
186 | // If Vy is more or equal Vx, we can't overflow, so set carry flag, otherwise clear it
187 | flag = (byte)(v[y] >= v[x] ? 1 : 0);
188 | v[x] = (byte)(v[y] - v[x]);
189 | v[0xf] = flag;
190 | break;
191 |
192 | case 0xe: // SHL Vx
193 | //v[x] = v[y];
194 | result = (v[x] & 128) >> 7;
195 | v[x] <<= 1;
196 | v[0xf] = (byte)result;
197 | break;
198 | }
199 | break;
200 |
201 | case 0x9: // SNE Vx, Vy
202 | if (v[x] != v[y])
203 | {
204 | pc += 2; // skip next instruction if not equal
205 | }
206 | break;
207 |
208 | case 0xa: // LD I, nnn
209 | i = (ushort)((param * 256) + data);
210 | break;
211 |
212 | case 0xb: // JP V0, nnn
213 | pc = (ushort)((param * 256) + data + v[0]);
214 | break;
215 |
216 | case 0xc: // RND Vx, byte
217 | v[x] = (byte)(rnd.Next(0, 255) & data);
218 | break;
219 |
220 | case 0xd: // DRW Vx, Vy, bytes
221 | if (CanDrawSprite)
222 | {
223 | v[0xf] = display.DrawSprite(v[x], v[y], data & 0xf, i);
224 | CanDrawSprite = false;
225 | }
226 | else
227 | {
228 | pc -= 2;
229 | }
230 | break;
231 |
232 | case 0xe: // Keyboard
233 | switch (data)
234 | {
235 | case 0x9e: // SKP Vx
236 | // Skip next instruction if key pressed
237 | if (keysPressed[v[x] & 0x0f])
238 | {
239 | pc += 2;
240 | }
241 | break;
242 |
243 | case 0xa1: // SKNP Vx
244 | // Skip next instruction if key not pressed
245 | if (!keysPressed[v[x] & 0x0f])
246 | {
247 | pc += 2;
248 | }
249 | break;
250 | }
251 | break;
252 |
253 | case 0xf: // Misc and keyboard
254 | switch (data)
255 | {
256 | case 0x7: // LD Vx, DT
257 | v[x] = dt;
258 | break;
259 |
260 | case 0xa: // LD Vx, K
261 | if (halted)
262 | {
263 | for (int k = 0; k < keysPressed.Length; k++)
264 | {
265 | if (keysPressed[k])
266 | {
267 | halted = false;
268 | v[x] = (byte)k;
269 | keysPressed[k] = false;
270 | return;
271 | }
272 | }
273 | }
274 |
275 | halted = true;
276 | pc -= 2;
277 | break;
278 |
279 | case 0x15: // LD DT, Vx
280 | dt = v[x];
281 | break;
282 |
283 | case 0x18: // LD ST, Vx
284 | st = v[x];
285 | break;
286 |
287 | case 0x1e: // ADD I, Vx
288 | i += v[x];
289 | break;
290 |
291 | case 0x29: // LD F, Vx
292 | i = (ushort)((v[x] & 0xF) * 5);
293 | break;
294 |
295 | case 0x33: // LD B, Vx
296 | ram.Ram[(i + 0) & 0xfff] = (byte)(v[x] / 100);
297 | ram.Ram[(i + 1) & 0xfff] = (byte)(v[x] / 10 % 10);
298 | ram.Ram[(i + 2) & 0xfff] = (byte)(v[x] % 10);
299 | break;
300 |
301 | case 0x55: // LD [I], Vx
302 | for (int reg = 0; reg <= x; reg++)
303 | {
304 | ram.Ram[(i + reg) & 0xfff] = v[reg];
305 | }
306 | i++;
307 | break;
308 |
309 | case 0x65: // LD Vx, [I]
310 | for (int reg = 0; reg <= x; reg++)
311 | {
312 | v[reg] = ram.Ram[(i + reg) & 0xfff];
313 | }
314 | i++;
315 | break;
316 | }
317 |
318 | break;
319 | }
320 | }
321 | }
--------------------------------------------------------------------------------
/Chip8/Display.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Chip8;
4 |
5 | public class Display(Memory ram)
6 | {
7 | private const uint Ink = 0xffffffff;
8 | private const uint Paper = 0xff000000;
9 | private const int ScreenWidth = 64;
10 | private const int ScreenHeight = 32;
11 |
12 | public readonly byte[] Pixels = new byte[ScreenWidth * ScreenHeight * sizeof(uint)];
13 |
14 | private readonly Memory ram = ram;
15 | private readonly byte[] screen = new byte[ScreenWidth * ScreenHeight];
16 |
17 | public byte DrawSprite(int x, int y, int height, ushort dataAddr)
18 | {
19 | x %= ScreenWidth;
20 | y %= ScreenHeight;
21 |
22 | int collision = 0;
23 |
24 | for (int dy = y; dy < y + height && dy < ScreenHeight; dy++)
25 | {
26 | byte bits = ram.Ram[dataAddr + dy - y];
27 | int yPos = dy * ScreenWidth;
28 |
29 | for (int dx = x; dx < x + 8 && dx < ScreenWidth; dx++)
30 | {
31 | int xyPos = yPos + dx;
32 | if ((bits & 0x80) != 0)
33 | {
34 | if (screen[xyPos] == 1)
35 | {
36 | collision = 1;
37 | }
38 |
39 | screen[xyPos] ^= 1;
40 | }
41 |
42 | bits <<= 1;
43 | }
44 | }
45 |
46 | return (byte)collision;
47 | }
48 |
49 | public void Clear()
50 | {
51 | Array.Clear(screen);
52 | }
53 |
54 | public void UpdatePixels(Span pixels)
55 | {
56 | for (int i = 0; i < pixels.Length; i++)
57 | {
58 | pixels[i] = screen[i] == 1 ? Ink : Paper;
59 | }
60 | }
61 | }
--------------------------------------------------------------------------------
/Chip8/Machine.cs:
--------------------------------------------------------------------------------
1 | using SFML.Graphics;
2 | using SFML.System;
3 | using SFML.Window;
4 | using System;
5 | using System.IO;
6 | using System.Runtime.InteropServices;
7 |
8 | namespace Chip8;
9 |
10 | internal class Machine
11 | {
12 | private readonly Cpu cpu;
13 | private readonly Memory ram;
14 | private readonly Display display;
15 | private readonly Audio audio;
16 | private readonly bool[] KeysPressed;
17 | private readonly string romName;
18 |
19 | public Machine(string rom)
20 | {
21 | KeysPressed = new bool[16];
22 | ram = new Memory();
23 | audio = new Audio();
24 | display = new Display(ram);
25 | cpu = new Cpu(display, ram, audio, KeysPressed);
26 |
27 | romName = rom;
28 | }
29 | public void Run()
30 | {
31 | var window = new RenderWindow(new VideoMode(1280, 640), "CHIP-8", Styles.Default);
32 | window.SetFramerateLimit(60);
33 | window.SetVerticalSyncEnabled(false);
34 |
35 | window.Closed += (s, e) => window.Close();
36 |
37 | window.KeyPressed += OnKeyPressed;
38 | window.KeyReleased += OnKeyReleased;
39 |
40 | Texture texture = new(64, 32);
41 | Sprite frameBuffer = new(texture);
42 | frameBuffer.Scale = new Vector2f(20, 20);
43 |
44 | using (var fs = File.Open(romName, FileMode.Open))
45 | {
46 | fs.Read(ram.Ram, 0x200, (int)fs.Length);
47 | }
48 |
49 | Clock fpsClock = new();
50 | var pixels = MemoryMarshal.Cast(display.Pixels.AsSpan());
51 |
52 | while (window.IsOpen)
53 | {
54 | float fps = 1 / fpsClock.Restart().AsSeconds();
55 |
56 | window.DispatchEvents();
57 |
58 | Console.SetCursorPosition(0, 2);
59 | Console.WriteLine("FPS: {0}", fps.ToString().PadRight(4));
60 |
61 | cpu.CanDrawSprite = true;
62 | for (int i = 0; i < 500 / 60; i++)
63 | {
64 | cpu.Decode();
65 | }
66 |
67 | display.UpdatePixels(pixels);
68 | texture.Update(display.Pixels);
69 | window.Draw(frameBuffer);
70 |
71 | window.Display();
72 | }
73 | }
74 |
75 | private static int GetKeyIndex(Keyboard.Key key)
76 | {
77 | return key switch
78 | {
79 | Keyboard.Key.X => 0,
80 | Keyboard.Key.Num1 => 1,
81 | Keyboard.Key.Num2 => 2,
82 | Keyboard.Key.Num3 => 3,
83 | Keyboard.Key.Q => 4,
84 | Keyboard.Key.W => 5,
85 | Keyboard.Key.E => 6,
86 | Keyboard.Key.A => 7,
87 | Keyboard.Key.S => 8,
88 | Keyboard.Key.D => 9,
89 | Keyboard.Key.Z => 10,
90 | Keyboard.Key.C => 11,
91 | Keyboard.Key.Num4 => 12,
92 | Keyboard.Key.R => 13,
93 | Keyboard.Key.F => 14,
94 | Keyboard.Key.V => 15,
95 | _ => -1
96 | };
97 | }
98 |
99 | private void OnKeyReleased(object sender, KeyEventArgs e)
100 | {
101 | int index = GetKeyIndex(e.Code);
102 | if (index != -1)
103 | {
104 | KeysPressed[index] = false;
105 | }
106 | }
107 |
108 | private void OnKeyPressed(object sender, KeyEventArgs e)
109 | {
110 | if (e.Code == Keyboard.Key.Escape)
111 | {
112 | (sender as Window).Close();
113 | return;
114 | }
115 |
116 | int index = GetKeyIndex(e.Code);
117 | if (index != -1)
118 | {
119 | KeysPressed[index] = true;
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/Chip8/Memory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Chip8;
4 |
5 | public class Memory
6 | {
7 | private static readonly byte[] fontData =
8 | [
9 | 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
10 | 0x20, 0x60, 0x20, 0x20, 0x70, // 1
11 | 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
12 | 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
13 | 0x90, 0x90, 0xF0, 0x10, 0x10, // 4
14 | 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
15 | 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
16 | 0xF0, 0x10, 0x20, 0x40, 0x40, // 7
17 | 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
18 | 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
19 | 0xF0, 0x90, 0xF0, 0x90, 0x90, // A
20 | 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
21 | 0xF0, 0x80, 0x80, 0x80, 0xF0, // C
22 | 0xE0, 0x90, 0x90, 0x90, 0xE0, // D
23 | 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
24 | 0xF0, 0x80, 0xF0, 0x80, 0x80 // F
25 | ];
26 |
27 | public Memory()
28 | {
29 | Ram = new byte[4096];
30 |
31 | // Copy font data to ram[0] for convenience
32 | Array.Copy(fontData, Ram, fontData.Length);
33 | }
34 |
35 | public byte[] Ram { get; set; }
36 | }
--------------------------------------------------------------------------------
/Chip8/Program.cs:
--------------------------------------------------------------------------------
1 | namespace Chip8;
2 |
3 | internal static class Program
4 | {
5 | private static void Main()
6 | {
7 | var machine = new Machine("4-flags.ch8");
8 | machine.Run();
9 | }
10 | }
--------------------------------------------------------------------------------