summaryrefslogtreecommitdiff
path: root/examples/noc/src/random_walk.zig
diff options
context:
space:
mode:
Diffstat (limited to 'examples/noc/src/random_walk.zig')
-rw-r--r--examples/noc/src/random_walk.zig60
1 files changed, 60 insertions, 0 deletions
diff --git a/examples/noc/src/random_walk.zig b/examples/noc/src/random_walk.zig
new file mode 100644
index 0000000..fff856e
--- /dev/null
+++ b/examples/noc/src/random_walk.zig
@@ -0,0 +1,60 @@
+//! Example 0.1: Random Walk. A walker takes a random step left, right, up
+//! or down each frame and leaves a black dot; the canvas is never cleared.
+//! The dots go into an offscreen image that keeps them (`f.target`).
+const std = @import("std");
+const sk = @import("sketch");
+
+pub const name = "random_walk";
+pub const width = 640;
+pub const height = 360;
+
+const Walker = struct {
+ x: i32 = width / 2,
+ y: i32 = height / 2,
+ rng: std.Random.Xoshiro256 = .init(1),
+
+ fn step(w: *Walker) void {
+ switch (w.rng.random().uintLessThan(u8, 4)) {
+ 0 => w.x += 1,
+ 1 => w.x -= 1,
+ 2 => w.y += 1,
+ else => w.y -= 1,
+ }
+ }
+};
+
+pub const State = struct {
+ walker: Walker = .{},
+ clock: sk.Clock = .{},
+};
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ for (0..s.clock.steps(in)) |_| s.walker.step();
+}
+
+pub const Session = struct {
+ trail: sk.Image = .none,
+ /// The walk again, as far as the trail shows it.
+ shadow: Walker = .{},
+ drawn: u64 = 0,
+};
+
+/// The trail is a cache of the walk, not State: after a jump (a seek, a
+/// load, a reload) it is painted again from the first step, so it shows
+/// what playing would have.
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
+ if (ss.trail == .none or f.in.jumped) {
+ if (ss.trail == .none) ss.trail = f.host.newImage(width, height);
+ ss.* = .{ .trail = ss.trail };
+ f.target(ss.trail);
+ f.clear(.white);
+ } else f.target(ss.trail);
+ while (ss.drawn < s.clock.count) : (ss.drawn += 1) {
+ ss.shadow.step();
+ f.fill(.{ .x = ss.shadow.x, .y = ss.shadow.y, .w = 1, .h = 1 }, .black);
+ }
+ // A `set` moved the walker off the walk: go on from there.
+ ss.shadow = s.walker;
+ f.target(.none);
+ f.image(ss.trail, .{ .x = 0, .y = 0, .w = width, .h = height }, .{});
+}