Number Guessing (Step by Step)

Article Info
Note
this are hints/notes on how to accomplish the guessing game task in the week 1 workshop. If you are new to C#, or arn’t sure where to start, this is intended as a 'step-by-step' guide through this part of the worksheet.

This is a step-by-step walkthrough of the code for guess.cs tasks.

Cleaning up Main

The first part asks you to remove contents of the existing Main method, the code will look something like this before we start the task.

I thought about getting you to create a new project, but the code we had to start with was introductory so it’s probably safe to just remove. You can refer to ealier in the worksheet if you need any of it for reference in this task.

If you deleted the contents of main

namespace COMP101_HelloWorld
{
    internal class Program
    {
        static void Main(string[] args){
        }
    }
}

Everything should look like when we started at this point, we can just write the code in the (now empty) Main method.

If you chose to rename the old main

I gave the option to rename the old main method if you wanted to keep it around, in that case, the code would look like this (depending on what you did to your old main):

namespace COMP101_HelloWorld
{
    internal class Program
    {
        static void Main(string[] args){
        }

        static void Main_old(string[] args){
            int myValue = 0; //(1)
            myValue += 42; //(2)

            Console.WriteLine("Hello, World! {0:D}", myValue); //(3)
        }
    }
}

We need to do this because C# runs the method called Main when the program starts, we want it to run the guessing game code we’re about to write, not the introduction.

Rationale for stucture

this is a peak behind the curtian - you don’t need to know any of this box, but I’m providing a rationale for why I’ve designed the workshop like this.

You may be wondering why I just got you to do that stuff if you’re just going to delete it - valid question.

The first part of this weeks' workshop is mostly around introducing you to what C# looks like (its syntax) and the variable types we need for this weeks session.

I’ve tried to only use one variable type (int) as we’ve not covered types yet. I do briefly mention bool later in passing — I do this to show that other types work exactly the same as ints do, and delibratly don’t call attention to it. Arguably string, but we only ever use that implicitly.

I put variables right up-front in the session - this is because if you’ve seen some python before I need to introduce you to the concept of a statically typed language (although I don’t actually call it that yet). Having just shown you variable declaration is different I then show you that assignment is the same — we can trust some of our pythonic initiation here, but not all of it.

Yes, I overthink my worksheet structure.

Creating a variable

The first task is to create a variable which stores a whole number (integer), in C-Sharp this is accomplished using the int keyword followed by the variable name. We can (but don’t have to) provide an initial value using an = followed by the value. It doesn’t matter what value we pick, so I picked 5.

int targetNumber = 5;

This must be put in the Main method (between the { and } in main).

Creating a Loop

I give three possible types of loop (while, for, foreach) in the lab script. The most explicit (easy to follow) is the while loop. The structure looks like this:

while ( true ) {
    // do processing here (next step)
}

This loop will run forever (as true is always true) - its more common to have a condition here, but we’ll look at this more in week 2.

In the main script, I created a bool variable to do this rather than just writing true, this was a hint for one of the extention tasks (you can set the variable to False to end the loop). I’ve simplified the version of the loop for this page, just to avoid the extra complexity.

I’m going to use break; to end the loop for this guide - using a variable is a bit cleaner when you have loops inside other loops (such as error handling or rounds).

Loop Structure

Note
you don’t need to understand loops too deeply for week 1, ideally, I would not have put any in this week, but I couldn’t make the guessing game work in a nice way without them.

The task outlines a set of steps which might make sense for our loop as a hint. We’ve not seen how to ask for user input yet, so for now, we’ll just assume the player guessed 0.

I’ve put how the code below maps to the requirements/hints as comments. Here is my rationale for each of requirements (and where it was introduced):

  • We saw how to prompt the user for input in 'Hello, World!' — System.WriteLine

  • We know how to create a variable of type int as well — int variableName

  • We don’t know how to ask the user for input (yet)

  • We are asked to create if statements - introduced in conditionals

while ( true ) {

    // Display a message using Console.WriteLine to prompt the user for a number
    System.WriteLine("Please provide a guess:");

    // Create a variable of type int to store the users guess, set it to any value for the time being
    int guess = 0; // TODO prompt user for input (next part)

    // Use an if statement to check if that number is the same as the target number
    if ( guess == targetNumber ) {
        System.WriteLine("Correct!");
        break;
    }

    // I'm NOT giving you the other two if statements (less than and greater) - write these now :)
}

To avoid providing all of the code for this worksheet, I’d like you to try and use the if statement I have given you to try and create a new if statement that checks if the value is larger and show a message if it is.

You can modify the value of guess in the code and run the code to check this works. Because it will always provide the same guess, it will run forever and you need to use the red square (stop) to stop the program.

Once you get this working (printing that the value is too big), do the same for when the value is too small.

User Input

To make our game functional, we’re going to need to ask for user input (from standard input). To ask for user input, you can use the code I give you in the main lab section.

Replace int guess = 0; in the code with the code to ask for a user input.

string? userGuessStr = Console.ReadLine();
int guess = userGuessStr == null ? 0 : int.Parse(userGuessStr);

I also monologue a bit about different ways of handling errors, and different ways of writing the above - probably safe to ignore that for now. If you want to use one of the other approaches (eg, if statement version) feel free to do so.

Run the game, it should be a kinda functional guessing game at this point. The rest of the session is designed as an exploration of ways in which can we use what we’ve just talked about (variables, printing, etc…​) to add new functionality.

At the highest-levels of the remaining tasks (eg, advanced) you will need to do some research on how best to do these.

Graduation Cap Book Open book GitHub Info chevron-right Sticky Note chevron-left Puzzle Piece Square Lightbulb Video Exclamation Triangle Globe