code me a very nice console application(game) in ZIg programming language
- User
code me a very nice console application(game) in ZIg programming language
- Assistant
Here's a simple Hangman game implemented in the Zig programming language. This console application allows the user to guess letters in a hidden word, with a limited number of attempts.
const std = @import("std"); const WordBank = [_][]const u8{ "zig", "programming", "language", "console", "application", "game", "hangman", "development" }; pub fn main() !void { var stdout = std.io.getStdOut().writer(); var stdin = std.io.getStdIn().reader(); const seed = std.time.ns(); var rng = std.rand.DefaultPrng.init(seed); // Select a random word from WordBank const index = rng.uintLessThan(WordBank.len); const word = WordBank[index]; var guessed = std.ArrayList(u8).init(std.heap.page_allocator); defer guessed.deinit(); var attempts: usize = 6; while (attempts > 0) { try stdout.print("Word: ", .{}); var all_guessed = true; // Display the word with guessed letters and underscores for missing letters for (word) |c| { if (guessed.items.contains(std.ascii.toLowercase(c))) { try stdout.print("{c} ", .{c}); } else { try stdout.print("_ ", .{}); all_guessed = false; } } try stdout.print("\n", .{}); // Check if all letters have been guessed if (all_guessed) { try stdout.print("Congratulations! You guessed the word.\n", .{}); break; } try stdout.print("Attempts left: {d}\n", .{attempts}); try stdout.print("Guess a letter: ", .{}); var buffer: [1]u8 = undefined; var read_bytes = try stdin.read(&buffer); if (read_bytes == 0 || buffer[0] == 0) { try stdout.print("No input read.\n", .{}); continue; } const guess = std.ascii.toLowercase(buffer[0]); // Validate that the input is an alphabetic character if (!std.ascii.isAlpha(guess)) { try stdout.print("Please enter a valid letter.\n", .{}); continue; } // Check if the letter has already been guessed if (!guessed.items.contains(guess)) { try guessed.append(guess); if (!std.mem.contains(u8, word, guess)) { attempts -= 1; try stdout.print("Wrong guess!\n", .{}); } } else { try stdout.print("You already guessed that letter.\n", .{}); } } // Game over message if (attempts == 0) { try stdout.print("Game over! The word was '{s}'.\n", .{word}); } }Explanation:
-
Imports and Constants:
std: Imports Zig's standard library.WordBank: An array containing words for the game to choose from.
-
Main Function:
- Standard I/O: Initializes
stdoutandstdinfor console output and input. - Random Number Generator: Uses the current time in nanoseconds as a seed to initialize the random number generator (
rng). - Select a Random Word: Picks a random index to select a word from
WordBank.
- Standard I/O: Initializes
-
Game Variables:
guessed: AnArrayListto keep track of the letters that the player has guessed.attempts: Sets the number of attempts the player has (starting at 6).
-
Game Loop:
- Display Word Status:
- Prints the word with guessed letters revealed and underscores for letters yet to be guessed.
- Checks if all letters have been guessed to determine if the player has won.
- Player Input:
- Prompts the player to guess a letter.
- Reads one character from standard input.
- Validates that the input is a single alphabetic character.
- Processing Guess:
- Converts the input letter to lowercase to ensure case-insensitive comparison.
- Checks if the letter has already been guessed.
- If the guess is incorrect (the letter is not in the word), decrements the
attemptscounter.
- Game Over Check:
- If
attemptsreaches zero, the game ends, and the correct word is revealed.
- If
- Display Word Status:
-
End of Game Messages:
- Displays a congratulatory message if the word is guessed.
- Shows a game over message if the player runs out of attempts.
Compiling and Running the Game:
To compile and run this Zig program, follow these steps:
-
Save the Code:
- Save the code above in a file named
hangman.zig.
- Save the code above in a file named
-
Open Terminal:
- Navigate to the directory containing
hangman.zig.
- Navigate to the directory containing
-
Compile the Program:
zig build-exe hangman.zig -
Run the Executable:
- On Linux or macOS:
./hangman - On Windows:
.\hangman.exe
- On Linux or macOS:
-
Play the Game:
- Follow the on-screen instructions to guess letters.
- Input a single letter when prompted.
- The game will display the current state of the word, the number of attempts left, and messages indicating the result of each guess.
Example Gameplay:
Word: _ _ _ _ _ _ _ _ _ _ _ Attempts left: 6 Guess a letter: a Wrong guess! Word: _ _ _ _ _ _ _ _ _ _ _ Attempts left: 5 Guess a letter: e Word: _ _ _ e _ _ _ e _ _ _ Attempts left: 5 Guess a letter: l Word: _ _ _ e l _ _ e _ _ _ Attempts left: 5 Guess a letter: development Please enter a valid letter. Word: _ _ _ e l _ _ e _ _ _ Attempts left: 5 Guess a letter: d Word: d _ _ e l _ _ e _ _ _ Attempts left: 5 Guess a letter: ...Notes:
-
Single Character Input:
- The game reads single characters from standard input. Ensure that when you input a letter, you press Enter afterward.
-
Case Insensitivity:
- The game converts all input letters to lowercase, so it doesn't matter if you input uppercase or lowercase letters.
-
Extending the Game:
- You can add more words to the
WordBankarray to increase the game's variety. - Adjust the
attemptsvariable to change the difficulty level.
- You can add more words to the
Learning Points:
-
Standard Library Usage:
- Leveraging Zig's standard library for I/O operations, random number generation, and character manipulation.
-
Control Structures:
- Utilizing loops and conditionals to control the game flow.
-
Data Structures:
- Using
ArrayListto manage dynamic arrays in Zig.
- Using
-
Error Handling:
- Applying
tryto handle potential errors from I/O operations and memory allocation.
- Applying
Conclusion:
This Hangman game provides a practical example of building a console application in Zig. It demonstrates fundamental programming concepts such as variables, control flow, input/output, and data structures within the context of an engaging and interactive game.
Feel free to experiment with the code to add new features or improve the game's functionality. Happy coding!
-