Number Guessing Game Beginner

GrianB

New member
Joined
Oct 18, 2019
Messages
4
Programming Experience
Beginner
I am trying to create a Number Guessing Game and I'm a little stuck...I have to create a Mystery Number Guessing Game that has two classes, one class being a test class. I have the following so far but its all on one Class(test). I am also having trouble with ending the application after it reaches its 5th attempt. My application needs to include:
1. Two Classes
2. A constructor that creates a random integer between 1-100 stored in an instance variable
3. At least one public Method
4. At least one public property

This is what I have so far.
C#:
using System;

class MysteryNumber
{
    public int RNumber { get; }// auto implemented property
    private int random;//instance variable
    
    public MysteryNumber(int myRand)//constructor
    {
        MyRand = myRand;
    }
}


=====================SEPARATE CLASS=============================

C#:
using System;

class MysteryNumberTest
{
    static void Main()
    {
        int myRand;
        Random randomNumbers = new Random();
        
        myRand = randomNumbers.Next(1, 100);
        
        int numberOfGuessesLeft = 4;
        int numberOfGuessesMade = 1;
        
        while (numberOfGuessesLeft <= 5)
        {
            Console.Write("Enter A Number Between 1 and 100: ");
            
            int guess = int.Parse(Console.ReadLine());
            
            guess = numberOfGuessesMade;
            
            if (numberOfGuessesMade == myRand)
            {
                Console.WriteLine($"Good Job! It only took {numberOfGuessesMade}");
            }
            else if (numberOfGuessesMade != myRand)
            {
                Console.WriteLine($"Sorry, Try Again. This is guess number {numberOfGuessesMade}, you have {numberOfGuessesLeft} left.");
                
                numberOfGuessesLeft = numberOfGuessesLeft - 1;
                numberOfGuessesMade = numberOfGuessesMade + 1;
            }
        }
        
        Console.ReadLine();
    }
}
 
Last edited by a moderator:
Hi and welcome to the forums. Please take the time to format your code using the code tags button. Formatting the code with code tags helps keep the proper indentation, as well as formatting it.

You've also posted this in the wrong forum, as this has nothing to do with C# discussion, and so belongs under console apps.
 
I have formatted your code appropriately, including with proper indentation and without loads of empty space. Please use the editor toolbar to format your posts appropriately, as you would in any other text editor, and also make sure that code is as readable as possible.

I have also moved your thread to a more appropriate form. A General form should only be used if there isn't a more specific forum that fits. Don;t just select the first one you come to.
 
As for the issue, your description is a bit vague. Firstly, you sat that all the code is in one class and yet I can see declarations for class MysteryNumber and class MysteryNumberTest. As for the rest, you seem to be saying "here's what I have to do, here's what I have done, tell me what to do". Instead of that, you should be telling us exactly what problem you're having with what specific aspect of the project. If you have multiple problems then you should create multiple threads, with each one focusing on a specific problem, providing all the information relevant to that problem and nothing that isn't.

One of the main reasons that beginners tend to have problems is that that try to treat every project as one big blob and do it all in one go. That rarely works. The fact that you have code that pretty covers the whole app but you have bots and pieces that you don;t really understand or that don't really work throughout is a demonstration of that. You should think of your application as a pipeline; as a series of boxes with pipes connecting each pair. Each box performs a task. Within a box, you might have smaller boxes performing smaller tasks. The first thing you need to do is look at the overall task you need top perform and break it down into smaller parts. Keep breaking those parts down into smaller and smaller parts until you can't go any further. You can now build each box independent of all the others. All you need to test a box is an understanding of what the possible inputs could be and what the outputs should be. As you build a box, if you encounter any issues with that part specifically, you should ask about that specific problem. When a box is working, you can put it aside and work on another box. As more and more boxes are completed, you can start joining some together with pipes and then test those subsets. Eventually, you'll have all boxes complete and you can hook everything together. The smaller the parts you break the problem into, the easier each part will be and the easier getting help with that part will be.
 
I have deleted your other thread because it really just repeated what you have here, plus the formatting was worse in some ways. One thing I will address is that you said that you don;t know how to make the two classes communicate. Yes, you do. You just don;t realise it because you don't really know what classes are. In the code you posted, what do you suppose this is doing:
C#:
Random randomNumbers = new Random();

myRand = randomNumbers.Next(1, 100);
That code is declaring a variable of type Random, creating an instance of the Random class and assigning it to the variable, then calling a method on that that object, passing it two arguments. Congratulations, you just made two classes communicate.

Class is used in this context much as it is in Dungeons & Dragons. In role-playing games you have classes of characters, the classics being warrior, mage and cleric Each class describes what characters of that type are, have and do. When you play a game, you choose a character class and then create a character of that type. You specify what it has and then you make it do things. Classes in programming are basically the same. The class describes what objects of that type are, have and do. In code, you create an instance of a type by invoking a class constructor with the new keyword. You then specify what it has by setting properties and you make it do things by calling methods.

In your case, you need to write your MysteryNumber class such that it represents something useful, then have your MysteryNumberTest class create an instance and make it do that useful thing. Think about classes in .NET that you have already used.
 
I'm still trying to figure out why you would be setting a variable from inside the constructor. If anyone can explain a practical reason for that, knock yourselves out...

A function with a return type would be a better use IMO.

Curious @GrianB - where did you get this assignment from?

At a glance, it looks like you started out alright, but kinda lost interest mid-way and are now looking for someone to finish it for you.

have your MysteryNumberTest class create an instance and make it do that useful thing
I also fail to see why you'd waste time instantiating and adding the irrelevant code for something so trivial, oh and sure, I guess its just for the purpose of the exercise, but its unnecessary, plus you could also just make it a static object instead.
 
I have deleted your other thread because it really just repeated what you have here, plus the formatting was worse in some ways. One thing I will address is that you said that you don;t know how to make the two classes communicate. Yes, you do. You just don;t realise it because you don't really know what classes are. In the code you posted, what do you suppose this is doing:
C#:
Random randomNumbers = new Random();

myRand = randomNumbers.Next(1, 100);
That code is declaring a variable of type Random, creating an instance of the Random class and assigning it to the variable, then calling a method on that that object, passing it two arguments. Congratulations, you just made two classes communicate.

Class is used in this context much as it is in Dungeons & Dragons. In role-playing games you have classes of characters, the classics being warrior, mage and cleric Each class describes what characters of that type are, have and do. When you play a game, you choose a character class and then create a character of that type. You specify what it has and then you make it do things. Classes in programming are basically the same. The class describes what objects of that type are, have and do. In code, you create an instance of a type by invoking a class constructor with the new keyword. You then specify what it has by setting properties and you make it do things by calling methods.

In your case, you need to write your MysteryNumber class such that it represents something useful, then have your MysteryNumberTest class create an instance and make it do that useful thing. Think about classes in .NET that you have already used.


Thank you jmcilhinney for the breakdown and assistance. I really do appreciate it and it helps bring some sense and clarity to it.
 
I'm still trying to figure out why you would be setting a variable from inside the constructor. If anyone can explain a practical reason for that, knock yourselves out...

A function with a return type would be a better use IMO.

Curious @GrianB - where did you get this assignment from?

At a glance, it looks like you started out alright, but kinda lost interest mid-way and are now looking for someone to finish it for you.


I also fail to see why you'd waste time instantiating and adding the irrelevant code for something so trivial, oh and sure, I guess its just for the purpose of the exercise, but its unnecessary, plus you could also just make it a static object instead.


This is an assignment from my college. I didn't lose interest in the project. I simply wanted to go to a forum and ask experts what I am doing wrong and to help me understand some things. As a full-time worker and full-time student I didn't see the harm in putting this question in a forum having already had a failed tutoring session at the school (the tutor wanted to discuss tools and methods that we didn't discuss in class) and re-reading several chapters multiple times to see if I can understand. Again, not looking for someone finish my homework assignments, just trying to find a convenient way to ask experts about something I am a beginner in, especially since my school is 35 miles from me, I go online primarily and I work 12 hour days.
 
I simply wanted to go to a forum and ask experts what I am doing wrong and to help me understand some things. As a full-time worker and full-time student I didn't see the harm in putting this question in a forum
Well then, you are clearly in the right place. This forum consists of experts and some of them have more than 20 years under their belt. Now see the flipside of your argument from my perspective...
  1. You didn't come here asking a specific question, but eluded to asking a few at once indirectly. Users seeking help need to be specific, and clearly explain what they are having problems with, which is something you did not do.
  2. What is the point in us telling you how your code works, or doesn't work? That is what a debugger and teacher is for, and if you still don't understand, I can only conclude you skipped a few lessons and therein lies the problem with understanding your current problems.
  3. It's often better for us to ask you what your code is meant to do that it does not do as you expected. This question gives us a sense of understanding as to how much you know about the current code. There is little hope in you grasping any advice obtained from any forums if you skipped a few lessons. If you do not know this, therein lies a problem with understanding again. It is pointless for us to explain advanced chapters of the language if basic principles were never learned properly or explained properly to you too begin with.
I simply wanted to go to a forum and ask experts what I am doing wrong and to help me understand some things.
I can tell you straight-out. The problem you likely have is the professor, or teacher who provides you with a poor assignment to learn from. Most of the school/course material I have stumbled upon over the years across a variety of these forums (which I contribute to on a daily basis) is actually piss poor. And on a number of times, I find myself either correcting the material people like your good-self submit for evaluation by us so called experts. Or I end up explaining why the material they've been given to study is tripe or of poor calibre. And I can tell you as a mater of personal opinion; after a while it gets a bit tedious seen these posts continuously popping up. And being completely honest with you, this is not a dig at you, but some friendly advice. School material provided in most of today's educational systems always appears to be outdated, poor quality, bad examples, or just shite. I could not try to persuade you enough to read all of the basic material provided on the MSDN website relating to your project, and follow the examples there instead of what they are giving you to work with, especially if you want to have professional up-to-date examples to follow and learn from. Question your professor or teacher on everything. The more you question, the more you will learn. Take what they tell you with a grain of salt, and when you come home, research what they told you in class, and look for problems with their teachings, because what you will commonly find, is they are not always correct in their teachings...

Again, its my opinion, but having a student instantiate a class to set a variable from a random number generator is a very poor example of when something should need to be instantiated or simply made static instead.

Btw, I wasn't the only one who thought your topic was a bit unclear either :
As for the issue, your description is a bit vague.
However, regarding your code :

Line 8 does not belong in the that method
Line 12, 13 should be properties and moved outside the method, perhaps even into your new class?
Add logic to exit line 15
Line 19 should be using Try Parse and not parse. It's cleaner this way and It won't throw an exception if the user input is invalid
This :
C#:
            int guess = int.Parse(Console.ReadLine());
            guess = numberOfGuessesMade;
Is irrelevant, consider rewriting the logic to subtract the guesses made, from a property with a default value of 5.
On line 23 why does numberOfGuessesMade compare to the random generator?
Move line 29 below 32. Why would you tell them the wrong amount of remaining guesses before it's calculated?

Make some edits, use your debugger and look at what your code is doing, apply your changes, and post them up if you still need help. There is a debugger tutorial in my signature should you need it. Lastly, how long do you think it will take you to guess the correct number between 1/100. Your teacher didn't think that one out very well...

One more thing, what book are you using at school to learn the language?
 
Personally, I would set up a two class system this way: Bourgeoisie and Proletariat. Oh, wait. Wrong kind of classes. :p

Seriously, though, there are many ways to fulfill the two class requirement. This is my take on separation of concerns: game state vs game UI. The game state is held in GuessingGame, while all the UI that drives the game is in GameUI.

C#:
enum Response { Correct, TooLow, TooHigh } 

class GuessingGame
{
    public bool IsGameOver { get; private set; }
    private int _secretNumber;
    private int _guessesRemaining;

    public GuessingGame()
    {
        // your code here
    }

    public Response Guess(int number)
    {
        // your code here 
    }
}

class GameUI
{
    static int PromptForInt(string prompt)
    {
        // your code here
    }

    static bool PromptForYesNo(string prompt)
    {
        // your code here
    }

    static void PlayGame()
    {
        var game = new GuessingGame();
        while (!game.IsGameOver)
        {
            switch (game.Guess(PromptForInt("Please enter your guess: ")))
            {
                case Response.TooLow: Console.WriteLine("Too low."); break;
                case Response.TooHigh: Console.WriteLine("Too high."); break;
                case Response.Correct: Console.WriteLine("Correct!"); break;
            }
        }
    }

    static void Main()
    {
        do
        {
            PlayGame();
        } while (PromptForYesNo("Do you want to play again? "));
    }
}

There is more than one way to skin a cat, though. Pick a way of organizing classes that makes sense to you, because ultimately you'll need to maintain the code until you can pass it on to some poor sap while you move on to do bigger and more interesting things. The more you design the code to make sense to you, the easier it will be to communicate that idea to your future maintainer. Beware: that future maintainer may end up being you again, so write your code well.
 
You practically wrote it all for him lol

I had something similar, and I think your way is better than what his professor wanted.
 
Personally, I would set up a two class system this way: Bourgeoisie and Proletariat. Oh, wait. Wrong kind of classes. :p

Seriously, though, there are many ways to fulfill the two class requirement. This is my take on separation of concerns: game state vs game UI. The game state is held in GuessingGame, while all the UI that drives the game is in GameUI.

C#:
enum Response { Correct, TooLow, TooHigh }

class GuessingGame
{
    public bool IsGameOver { get; private set; }
    private int _secretNumber;
    private int _guessesRemaining;

    public GuessingGame()
    {
        // your code here
    }

    public Response Guess(int number)
    {
        // your code here
    }
}

class GameUI
{
    static int PromptForInt(string prompt)
    {
        // your code here
    }

    static bool PromptForYesNo(string prompt)
    {
        // your code here
    }

    static void PlayGame()
    {
        var game = new GuessingGame();
        while (!game.IsGameOver)
        {
            switch (game.Guess(PromptForInt("Please enter your guess: ")))
            {
                case Response.TooLow: Console.WriteLine("Too low."); break;
                case Response.TooHigh: Console.WriteLine("Too high."); break;
                case Response.Correct: Console.WriteLine("Correct!"); break;
            }
        }
    }

    static void Main()
    {
        do
        {
            PlayGame();
        } while (PromptForYesNo("Do you want to play again? "));
    }
}

There is more than one way to skin a cat, though. Pick a way of organizing classes that makes sense to you, because ultimately you'll need to maintain the code until you can pass it on to some poor sap while you move on to do bigger and more interesting things. The more you design the code to make sense to you, the easier it will be to communicate that idea to your future maintainer. Beware: that future maintainer may end up being you again, so write your code well.


Thank you for helping me out. I really do appreciate it. Hopefully one day I will do you all proud and become a self sufficient programmer, lol.
 
@GrianB - stop listening to your professors and educate yourself on the subjects he wants you to learn, and trust me, you will be twice as smart, and then you would make us proud.

MSDN is your best resource for learning, then us, if you need futher explaining of something which may not be obviously clear to you on MSDN. ;)

Good luck with the studies.
 
Topic from 2019?

Answer Mar 28, 2019 with "goto" disabled
and I created new version with While

Computer guessing number from 0 to billion to 10^9
by logarithmic time by 30 steps
C#:
using System; using System.Text; //daMilliard.cs
namespace DANILIN // rextester.com/DYVZM84267
{ class Program
    { static void Main(string[] args)
        { Random rand = new Random();int t=0;
int h2=100000000; int h1=0; int f=0;
int comp = rand.Next(h2);
int human = rand.Next(h2);
while (f<1)
{ Console.WriteLine();Console.Write(t);
Console.Write(" {0}",comp); 
Console.Write(" {0}",human);
if(comp < human)
{ Console.Write(" MORE");
int a=comp; comp=(comp+h2)/2; h1=a; }
else if(comp > human)
{ Console.Write(" less");
int a=comp; comp=(h1+comp)/2; h2=a;}
else {Console.Write(" win by ");
Console.Write(t); Console.Write(" steps");f=1;}
t++; }}}}
C#:
0 94799478 47553217 less
1 47399739 47553217 MORE
2 71099608 47553217 less
3 59249673 47553217 less
...
24 47553221 47553217 less
25 47553218 47553217 less
26 47553217 47553217 win by 26 steps
 
And how does that satisfy the need for two classes?
 

Latest posts

Back
Top Bottom