A CHIP-8 interpreter needs a display and keyboard input before it can run its first instruction. Raylib supplies cross-platform APIs for windows, graphics, input, and sound. It is a C library, but Zig can use it directly. section 6.4
For a reproducible build, fetch a Raylib source archive pinned to a commit. `zig fetch` records the dependency and its hash in `build.zig.zon`; replace `COMMIT_HASH` with the chosen commit. section 6.4.1
$ zig fetch --save=raylib github.com/raysan5/raylib/archive/COMMIT_HASH.tar.gz
Fetch Raylib and save it as a Zig dependency. section 6.4.1
Raylib includes a maintained Zig build file. In the application’s build script, resolve the dependency with the selected target and optimization settings, retrieve its `raylib` artifact, and link that artifact to the application module. section 6.4.1
Listing 6.10 Building our runtime with Raylib
const std = @import("std");
pub fn build(b: *std.Build) void {
// ... vm and tests ...
const raylib = b.dependency("raylib", .{ #1
.target = target,
.optimize = optimize,
});
const raylib_lib = raylib.artifact("raylib"); #2
const app_mod = b.createModule(.{ #3
.root_source_file = b.path("src/app.zig"),
.target = target,
.optimize = optimize,
});
app_mod.addImport("vm", vm_mod); #4
app_mod.linkLibrary(raylib_lib); #5
const app = b.addExecutable(.{ #6
.name = "chip8-runtime",
.root_module = app_mod,
});
b.installArtifact(app);
#7
const run_app = b.addRunArtifact(app);
const run_app_cmd = b.step("run", "Run the chip8 runtime");
run_app_cmd.dependOn(&run_app.step);
}
A CHIP-8 runtime build links Raylib and adds a run step. section 6.4.1
Raylib’s minimal framework expects an application to configure the library, create a window, and run a frame loop. Zig’s `@cImport` and `@cInclude` bring in `raylib.h` so Zig code can call the C API. section 6.4.2
Listing 6.11 All your window
const c = @cImport({ #1
@cInclude("raylib.h"); #2
});
pub fn main() !void {
c.InitWindow(640, 480, "All your window are belong to us!"); #3
defer c.CloseWindow(); #4
c.SetTargetFPS(60); #5
while (!c.WindowShouldClose()) { #6
c.BeginDrawing(); #7
defer c.EndDrawing(); #7
c.ClearBackground(c.BLACK); #8
}
}
A complete blank-window loop imports the header, opens a window, targets 60 frames per second, and clears each frame. section 6.4.2
The loop runs until `WindowShouldClose` reports that it is time to stop. Each iteration begins drawing, clears the background, and ends drawing with `defer`; another `defer` closes the window when `main` exits. From this small loop, add the display and input behavior the interpreter needs. section 6.4.2 section 6.4
