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
|
//! 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 }, .{});
}
|