Building Pong with Zig and Raylib #5: Show Score with dvui
In this episode, I finally add a score display to Pong using DVUI, a native Zig
UI framework. The scoring logic was already in place - now it’s time to show it
on screen.
Extract out Game struct
One of the structural changes I wanted to make to tidy up the code was to pull
out the game logic into its own struct. This change helps to declutter the
main.zig file, leading the way to add in the dvui scaffolding.
This refactor pulls the update and render logic into a Game struct, which
helps declutter main.zig and sets up a better foundation for UI work.
vargpa:std.heap.GeneralPurposeAllocator(.{})=.init;constallocator=gpa.allocator();defer_=gpa.deinit();//--------------------------------------------------------------------------
// init Raylib backend
// init() means the app owns the window (and must call CloseWindow itself)
varbackend=RaylibBackend.init(allocator);deferbackend.deinit();backend.log_events=true;// init dvui Window (maps onto a single OS window)
// OS window is managed by raylib, not dvui
varwin=trydvui.Window.init(@src(),allocator,backend.backend(),.{});deferwin.deinit();
Pre-render
1
2
3
4
5
// marks the beginning of a frame for dvui, can call dvui functions after this
trywin.begin(std.time.nanoTimestamp());// send all Raylib events to dvui for processing
_=trybackend.addAllEvents(&win);
Post-render
1
2
3
4
5
6
7
8
9
10
_=trywin.end(.{});// cursor management
if(win.cursorRequestedFloating())|cursor|{// cursor is over floating window, dvui sets it
backend.setCursor(cursor);}else{// cursor should be handled by application
backend.setCursor(.arrow);}
Show Score
We can now show the score using dvui.label with positioning hardcoded to about
25% and 75% across the screen. There may be a better way to position it but it
works well enough for now.
I had to generate an id for the label so that they were unique. I generated it
the x-position using @intFromFloat().