Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Using System; includes all the libraries that we will use
- using System;
- // Namespace organizes your code
- namespace ProgrammingTutorial
- {
- // In c# all code has to go inside a class
- class Program
- {
- //Random Class to generate random numbers
- static Random r = new Random();
- //Function that returns a random number that we can use
- public static int GetRandomNumber(int min, int max)
- {
- return r.Next(min, max + 1);
- }
- // Function to display text to the console
- public static void Say(string message)
- {
- Console.WriteLine(message);
- }
- // Input validation to get a number from the user
- public static int AskForNum(string optionalMessage = "")
- {
- while(true)
- {
- string s = Console.ReadLine();
- if(int.TryParse(s, out int x))
- {
- return x;
- }
- if(!string.IsNullOrEmpty(optionalMessage))
- Say(optionalMessage);
- }
- }
- //This is main starting point for your program
- public static void Main(string[] args)
- {
- while(true)
- {
- Say("Hello human! Would you like to play a game? Enter 1 to play!");
- int x = AskForNum("That wasn't a vaild response!");
- //if x is equal to 1 we play game, else we quit
- if(x == 1)
- {
- //store a random number for the user to guess
- int number = GetRandomNumber(1, 100);
- while(true)
- {
- Say("Ok! I am guessing of a number between 1 and 100! Can you guess it!?");
- //make the user input a guess
- int guess = AskForNum("Guess a proper number!");
- //then we compare the guess to the computer's number
- if(guess == number)
- {
- //if they guess right, they win!
- Say("You guessed the number correctly!");
- //quit the current game loop
- break;
- }
- if(guess > number)
- {
- //too high!
- Say("Too high! Guess again!");
- }
- else if(guess < number)
- {
- //too low!
- Say("Too low! Guess again!");
- }
- }
- }
- else
- {
- Say("Goodbye!");
- //break out of the while loop
- return;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement