A different version of your code with some improvements:

import std.stdio, std.cstream, std.random;

void main() {
    uint chosen = uniform(1, 21);

    writeln("This is a guessing game");
    writeln("I have chosen a number between 1 and 20" ~
            " which you must guess");

    int guess = 0;

    foreach_reverse (i; 1 .. 4) {
        writefln("You have %s tr%s left.", i, i == 1 ? "y" : "ies");
        write("enter a guess: "); // prompt for a guess
        scanf("%d", &guess); // Read a guess

        // check if guess correct
        if (guess == chosen) {
            writefln("\nYou guessed it!");
            return;
        }

        // Check for an invalid guess
        if (guess < 1 || guess > 20) // you can add brackets here if you want
            writeln("I said between 1 and 20.");
        else
            writefln("Sorry. %s is wrong.", guess);
    }

    writefln("You have had three tries and failed. The number was %s", chosen);

    din.getc(); // useless?
}

Bye,
bearophile

Reply via email to