Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Generating random numbers


Random numbers are commonly necessary in computer programs. Phobos' std.random module offers a variety of random number generators and other functions related to randomization. Here, we'll create a little number guessing game with a replay function. The user guesses the generated number, and then the program tells them if they were high or low.

How to do it…

Let's generate random numbers by executing the following steps:

  1. Create a random number generator, seeding it with the replay value, if given, or unpredictableSeed for a new game.

  2. Generate a random number between 0 and 100.

  3. Ask the user for their guess. Tell them if they were low or high and let them continue trying until they get it. Save each line of user input to the replay file.

  4. When the user is done playing, let them know how many tries they took to get the correct number.

The code is as follows:

import std.random, std.conv, std.string, std.stdio;

int playRound(ref Random generator, File userInput, File saveFile...