So, objects are not too complicated, they're just a group of related variables, possibly with some subroutines ("methods") that are somehow related.
So you might have something like this:
So then you could call this like:Code://Declare a class, which describes what types of data an object stores and the methods you might call class NumberGuessingGame { public bool gameIsOver; //Public means I can read this variable from a subroutine outside the class private int randomNumber; //Private means I can only read this variable from inside the class //A random number generator Random rng; //A constructor, which we will call to create a new NumberGuessingGame public NumberGuessingGame() { gameIsOver = false; //We haven't guessed the number yet, so the game still goes on rng = new Random(); //Get a random number generator for this instance randomNumber = rng.Next(0, 10); //Get a random number between 0 and 9, inclusive } //Then we'll create a method that returns TRUE if a guess is correct public bool makeGuess(int guessedNumber) { //If the number we guessed is equal to the randomNumber stored in this object (this is a reserved keyword) if( guessedNumber == this.randomNumber) { this.gameIsOver = true; return true; } //Otherwise, the game continues and the guess was wrong return false; } //Or maybe we want to be able to give a string as a guess and have it interpret it as a number public bool makeGuess(string guessedNumber) { //Call the makeGuess subroutine associated with THIS object return this.makeGuess(Int32.parse(guessedNumber)); } }
Does that make it a little more clear? You could, in principle, have several games going at the same time by declaring several instances (objects) of the NumberGuessingGame class:Code:public static void main(string[] args) { //Make a new guessing game instance //An instance is a SPECIFIC collection of information //For example, you might have written a "class" representing book with variables like title, year of publication, etc //But an INSTANCE of that class is data representing some specific book (e.g. Moby Dick) using the "Book" class NumberGuessingGame myGame = new NumberGuessingGame(); //Then loop until you win while( ! myGame.isGameOver ) { Console.Write("Guess a number: "); string myGuess = Console.ReadLine(); //Then check your guess myGame.makeGuess(myGuess); } //Loop until the game is over //When they finally guess the number, display a congratulatory message and exit Console.WriteLine("You win!"); }
Hope that helps! Try making modifications until you understand.Code:NumberGuessingGame game1 = new NumberGuessingGame(); NumberGuessingGame game2 = new NumberGuessingGame(); //Code to play the game, separately, goes here... game1.guess("1") //Guess that game1's secret variable is 1... //...etc...
Hopefully there are no syntax errors, but I pretty much just typed code into the window, so it's possible there might be some typos... (hopefully not though).




Reply With Quote
