Number guessing game Exercise

In case you get stuck anywhere, don't be afraid to ask the coaches! They are here to help and will gladly explain everything to you!

Take notes during the exercises. Even if you never look at them again, they will help you memorise things!

For these exercises, you will use your editor (Visual Studio Code or similar).

First, create an empty file with a meaningful name for this exercise, for example number_guessing.rb. Note the file extension .rb! Also remember what folder you saved your file in. It makes sense to create a folder for each lesson of the course.

Then, use cd in the command line to change to that folder. When you run ls you should see your file there.

Now you can run your Ruby program with ruby number_guessing.rb in the command line.

Repeat the above steps and remember to save your file in the editor before running it!

Let’s build a number guessing game. Here’s how it works:

When our program starts we think of a random number, like this:

secret_number = rand(100)

With rand(100), Ruby picks a random number between 0 and 100 for us.

The user can then enter a number and we will tell her whether it’s smaller or greater than the secret number we stored in the beginning. When the user is wrong, she can guess again as long as she wants. If she guesses the number, the game is over and we congratulate her.

Example interaction (user-entered text is bold):

Welcome to the number guessing game!
Make a guess: 50
The secret number is smaller!
Make a guess: 25
The secret number is smaller!
Make a guess: 12
The secret number is smaller!
Make a guess: 6
The secret number is smaller!
Make a guess: 4
The secret number is bigger!
Make a guess: 5
Congratulations! You guessed the secret number!

Hint 1: While you are developing the program, print out the secret number. This way it’s much easier to see what’s going on. When everything works, you can just remove that line of code and your game is ready.

Hint 2: Remember the frustration curve! Try out your code after every small change to see if things are working and if you’re getting closer to the goal.