Open-source News

Learn to code a simple game in Zig

opensource.com - Mon, 01/30/2023 - 16:00
Learn to code a simple game in Zig Moshe Zadka Mon, 01/30/2023 - 03:00

Writing the same application in multiple languages is a great way to learn new ways to program. Most programming languages have certain things in common, such as:

  • Variables
  • Expressions
  • Statements

These concepts are the basis of most programming languages. Once you understand them, you can take the time you need to figure out the rest.

Furthermore, programming languages usually share some similarities. Once you know one programming language, you can learn the basics of another by recognizing its differences.

A good tool for learning a new language is by practicing with a standard program.
This allows you to focus on the language, not the program's logic. I'm doing that in this article series using a "guess the number" program, in which the computer picks a number between 1 and 100 and asks you to guess it. The program loops until you guess the number correctly.

This program exercises several concepts in programming languages:

  • Variables
  • Input
  • Output
  • Conditional evaluation
  • Loops

It's a great practical experiment to learn a new programming language.

Guess the number in Zig basic

Zig is still in the alpha stage, and subject to change. This article is correct as of zig version 0.11. Install zig by going to the downloads directory and downloading the appropriate version for your operating system and architecture:

const std = @import("std"); fn ask_user() !i64 { const stdin = std.io.getStdIn().reader(); const stdout = std.io.getStdOut().writer(); var buf: [10]u8 = undefined; try stdout.print("Guess a number between 1 and 100: ", .{}); if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| { return std.fmt.parseInt(i64, user_input, 10); } else { return error.InvalidParam; } } pub fn main() !void { const stdout = std.io.getStdOut().writer(); var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; try std.os.getrandom(std.mem.asBytes(&seed)); break :blk seed; }); const value = prng.random().intRangeAtMost(i64, 1, 100); while (true) { const guess = try ask_user(); if (guess == value) { break; } const message = if (guess < value) "low" else "high"; try stdout.print("Too {s}\n", .{message}); } try stdout.print("That's right\n", .{}); }

The first line const std = @import("std"); imports the Zig standard library.
Almost all programs will need it.

The ask_user function in Zig

The function ask_user() returns a 64-bit integer or an error. This is what the ! (exclamation mark) notes. This means if there is an I/O issue or the user enters an invalid input, the function returns an error.

The try operator calls a function and return its value. If it returns an error, it immediately returns from the calling function with an error. This allows explicit, but easy, error propagation. The first two lines in ask_user alias contains some constants from std.
This makes the following I/O code simpler.

This line prints the prompt:

try stdout.print("Guess a number between 1 and 100: ", .{});

It automatically returns a failure if the print fails (for example, writing to a closed terminal).

This line defines the buffer into which user input is read:

var buf: [10]u8 = undefined;

The expression inside the if clause reads user input into the buffer:

(try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input|

The expression returns the slice of the buffer that was read into. This is assigned to the variable user_input, which is only valid inside the if block.

The function std.fmt.parseInt returns an error if the number cannot be parsed.
This error is propagated to the caller. If no bytes have been read, the function immediately returns an error.

Programming and development Red Hat Developers Blog Programming cheat sheets Try for free: Red Hat Learning Subscription eBook: An introduction to programming with Bash Bash shell scripting cheat sheet eBook: Modernizing Enterprise Java An open source developer's guide to building applications The main function

The function begins by getting a random number. It uses std.rand.DefaultPrng.

The function initializes the random number generator with std.os.getrandom. It then uses the generator to get a number in the range of 1 to 100.

The while loop continues while true is true, which is forever. The only way out is with the break, which happens when the guess is equal to the random value.

When the guess is not equal, the if statement returns the string low or high depending on the guess. This is interpolated into the message to the user.

Note that main is defined as !void, which means it can also return an error. This allows using the try operator inside main.

Sample output

An example run, after putting the program in main.zig:

$ zig run main.zig Guess a number between 1 and 100: 50 Too high Guess a number between 1 and 100: 25 Too low Guess a number between 1 and 100: 37 Too low Guess a number between 1 and 100: 42 Too high Guess a number between 1 and 100: 40 That's rightSummary

This "guess the number" game is a great introductory program for learning a new programming language because it exercises several common programming concepts in a pretty straightforward way. By implementing this simple game in different programming languages, you can demonstrate some core concepts of the languages and compare their details.

Do you have a favorite programming language? How would you write the "guess the number" game in it? Follow this article series to see examples of other programming languages that might interest you!

Practice programming in Zig by writing a "guess the number" game.

Image by:

Ray Smith

Programming What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

9 Best Google Drive Clients for Linux in 2023

Tecmint - Mon, 01/30/2023 - 14:53
The post 9 Best Google Drive Clients for Linux in 2023 first appeared on Tecmint: Linux Howtos, Tutorials & Guides .

One of the best cloud storage contenders to emerge is Google Drive – the popular cloud storage application that allows you to store data and access it from a Google account securely. Unfortunately, despite

The post 9 Best Google Drive Clients for Linux in 2023 first appeared on Tecmint: Linux Howtos, Tutorials & Guides.

GIMP 3.0 Aiming To Release In 2023

Phoronix - Mon, 01/30/2023 - 13:00
The long elusive GIMP 3.0 release that overhauls the UI and ports from GTK2 to GTK3 along with a wealth of other changes after being talked about for a decade could finally see its stable release this year...

Unlock your business potential with open leadership

Red Hat News - Mon, 01/30/2023 - 08:00
<p>When a leader of any kind begins to take on transforming or modernizing their business, whether it’s a small team or an entire organization, it requires change in multiple directions. What was successful in the past might not work in the changing volatile, uncertain, complex and ambiguous (VUCA) world anymore. Leadership can be practiced at every level of an organization irrespective of the role, title or position, by both people managers and individual contributors alike. Leadership is not the same thing as management,especially in organizations using open leadership, where

Linux 6.2-rc6 Released & It's Suspiciously Small

Phoronix - Mon, 01/30/2023 - 06:50
Linus Torvalds just released the sixth weekly RC of Linux 6.2 and it's coming in unusually light...

Budgie 10.7 Released With Big Improvements To This Linux Desktop

Phoronix - Mon, 01/30/2023 - 05:31
Budgie 10.7 is out today as the newest feature release to this open-source desktop environment that was originally developed as part of the Solus Linux distribution...

Cairo Graphics Library Drops OpenGL Support After A Decade Of Inactivity

Phoronix - Sun, 01/29/2023 - 22:00
The Cairo graphics library that provides a vector graphics based API and in turn having a number of different back-ends for software/hardware acceleration, which in turn is used by a variety of different desktop applications, has removed its OpenGL support...

Coreboot 4.19 Released With AMD Mayan Motherboard, MSI Alder Lake Board

Phoronix - Sun, 01/29/2023 - 20:24
Coreboot 4.19 is now available as the latest tagged release for this prominent open-source project allowing various motherboards with their proprietary firmware/BIOS to be replaced by this free software solution...

RADV Graphics Pipeline Library Support Becoming Speedy, Aims For Mesa 23.1 Promotion

Phoronix - Sun, 01/29/2023 - 20:17
The Mesa Radeon Vulkan "RADV" driver's implementation of the graphics pipeline library (VK_EXT_graphics_pipeline_library) is becoming much faster thanks to fast-linking and various pending fixes. In turn this will get games making use of the extension the ability to ideally have no shader pre-caching while still enjoying no in-game stuttering. Valve's Linux graphics driver developers working on RADV have been working through some issues with the RADV graphics pipeline library and for Mesa 23.1 looks like it could be in good shape...

LibreELEC 11 Beta 1 Released As Linux OS Built Around Kodi 20 - Adds HDR For Intel & AMD

Phoronix - Sun, 01/29/2023 - 19:24
Building off the release of the Kodi 20 HTPC/PVR software that released earlier this month, LibreELEC 11 Beta 1 is now available as a Linux distribution built around Kodi 20...

Pages