www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Minimal guessing game

Any suggestions you can give for this code?:

```
import std.conv : to, ConvException;
import std.string : strip;
import std.stdio : writeln, write, readln;
import std.random : uniform;

enum GiveUpCode = 500;

int generateNumber() {
     return uniform(1, 100);
}

void printMessage(string message) {
     writeln(message);
}

void gameStart() {
     int number = generateNumber();
     int tries = 0;
     int guess;

     do {
         write("Guess a number between 1 and 100: ");
         try {
             guess = readln().strip().to!int;

             if (guess == GiveUpCode) {
                 printMessage("You gave up! The number was: " ~ 
to!string(number) ~ ". " ~ (tries == 0 ? "Don't give up that 
easy!" : "But nice try, you can try again if you like!"));
                 return;
             }

             if (guess < 1 || guess > 100) {
                 printMessage("Please enter a number between 1 and 
100 or enter '" ~ to!string(GiveUpCode) ~ "' to exit the game. 
Try again, please.");
                 continue;
             }
         } catch (ConvException e) {
             printMessage("Do not enter letters, signs, no blank 
spaces, or something else that isn't a number! Try again!");
             continue;
         }

         tries++;

         if (guess < number) {
             printMessage("Too low. Try again.");
         } else if (guess > number) {
             printMessage("Too high. Try again.");
         } else {
             printMessage("Congratulations! You guessed the number 
correctly in " ~ to!string(tries) ~ (tries == 1 ? " attempt!" : " 
tries!"));
         }
     } while (guess != number);

     printMessage("Thanks for playing!");
}

int main() {
     printMessage("Welcome to the number guessing game! If you 
guess the number correctly, you win!.\nIf you can't guess the 
number, you can enter '" ~ to!string(GiveUpCode) ~ "' to exit the 
game.");
     gameStart();
     return 0;
}
Dec 27 2023