CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2012
    Posts
    2

    Creating a random number game as a client/server game

    Good evening everyone,

    I have been tasked for a job interview as a junior developer to create a game with the following parameters:

    • Listen on a specific port
    • Allow multiple clients to connect at once
    • Application client, which is responsible for connecting to server, interpreting the commands, and sending commands to the server
    • Client will ask user for lower number and higher number of the guessing game
    • Client will then ask user for their guess
    • Client will tell the user if their guess is too high, too low, or correct.
    • Once they guess the correct number, the client will then tell the user the number of trieds they took to find that number
    • The game then starts over.
    • *Side: I also want to add an option to close the game at anytime


    I am not looking for someone to tell me the EXACT approach to this. I am new to the coding world (I dove into C++ and Visual Basic about 9 years ago in high school; haven't touched it since), and have become intrigued at the fundamentals behind it. What I am looking for is some reference materials that might show examples of how this would be accomplished.

    Does anyone know of a website or published materials that would help me on this adventure?

    Thanks for your time in reading this post,

    KungPoo

  2. #2
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Creating a random number game as a client/server game

    Well, you can check these out to see how to create a client-server application using TCPClient and TCPListener ( (1) code-project article, (2) MSDN example (scroll down)).

    You will first need to figure out how the "gameplay" is going to work. If it was not a client-server app, you'd first have to generate a random number (use Random class, and it's Next() method). Then you'd enter a loop that would do this:
    • Ask the user to guess the number.
    • Read the input.
    • Increment the variable that stores number of tries.
    • Compare; if (1) target number is smaller/greater, tell the user that it is smaller/greater, if (2) the user got it right, congrat the user and end the game, and (3) if the user entered "exit" (for example), end the game.


    Now you need to adapt this to work over TCP, by sending and reading data; you'll also need to figure out how to convert data back and forth.

    Have you tried anything so far? What part are you having the most problems with. Take it step by step, solving one thing at a time? Can you show us some code, or provide more details at what areas you need help specifically?

  3. #3
    Join Date
    Sep 2012
    Posts
    2

    Re: Creating a random number game as a client/server game

    I decided to try to make it just as a standalone console application to make sure that I am doing it properly, and then move into the server/client relationship.

    Here is what I have so far.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string userChoice = ("");
                while (userChoice == "")
                {
                Thread.Sleep(1000);
                Console.WriteLine("Hello. Welcome to the World of Random Numbers. Please select an option.");
                Console.WriteLine("");
                Console.WriteLine("1. Start random number game.");
                Console.WriteLine("2. Instructions.");
                Console.WriteLine("3. Exit.");
                
                
                    userChoice = Console.ReadLine();
    
                    {
                        if (userChoice == "2")
                        {
                            Console.WriteLine("The server will ask you for a higher and lower number. Please select the range");
                            Console.WriteLine("of the game you would like to play.");
                            userChoice = ("");
                        }
                        else if (userChoice == "3")
                        {
                            Console.WriteLine("Thanks for coming. Have a great day.");
                            Thread.Sleep(2000);
                            Environment.Exit(1);
                            userChoice = ("");
                        }
                        else if (userChoice == "1")
                        {                     
                            PlayGame myGame = new PlayGame();
                            string playAgain = "y";
                            while (playAgain == "y")
                                
                            {
    
                                Console.WriteLine("Please enter the lowest number in the guessing game...");
                                myGame.userLow = Console.Read();
                                Console.WriteLine("Please enter the highest number in the guessing game...");
                                myGame.userHigh = Console.Read();
                                Console.WriteLine("Ok, I have picked a random number between " + myGame.userLow + "and" + myGame.userHigh + ". Please make a guess at which number I have chosen");
                                myGame.userGuess = Console.Read();
                                if (myGame.userGuess == myGame.serverNumber)
                                {
                                    Console.WriteLine("Congratulations! You guess the correct number!");
                                    Console.WriteLine("Would you like to play again?");
                                    playAgain = Console.ReadLine();
                                }
                                else if (myGame.userGuess != myGame.serverNumber)
                                {
                                    Console.WriteLine("Sorry, please try again...");
                                    myGame.userGuess = Console.Read();
                                }
                            }
                            
                        }
                        else
                        {
                            Console.WriteLine("Sorry, that is not a valid option. Please try again");
                            userChoice = ("");
    
                        }
                    }
    
                }
    
            }
    
        }
    }

    After these lines:

    Code:
    Console.WriteLine("Please enter the lowest number in the guessing game...");
                                myGame.userLow = Console.Read();
                                Console.WriteLine("Please enter the highest number in the guessing game...");
                                myGame.userHigh = Console.Read();
    I need to have int serverNumber generated as a rnadom number between userLow and userHigh, but I keep getting an error stating that I cannot implicitly convert string to int, and vice versa if I try any other ways.

  4. #4
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Creating a random number game as a client/server game

    OK. A few tips:

    To create a random number, use the Random class I linked to in my previous post. Since you're storing the low & high limits of the range in your PlayGame instance, it's best to generate the random number from within that class.

    Add a Random variable as a member field, somewhere at the top of your class:
    private Random rnd = new Random();

    And then add this method to it:
    Code:
    public void GenerateRandomNumber()
            {
                serverNumber = rnd.Next(userLow, userHigh + 1);
            }
    The Next(low, high) method of the Random class will create a random number between low and high, including low, but excluding high - which is why I used userHigh + 1.
    You then call this method once you obtain userLow and userHigh like this:
    myGame.GenerateRandomNumber();

    As for string-to-int conversions; C# is strongly typed, so it doesn't allow potentially unsafe conversions to happen implicitly. What if, instead of a number required of him, the user entered, for example: "Hah! This is gonna crash that program! >" ?

    So, there are various ways to safely convert from a string to an int - in your case, you'll probably wanna use the TryParse() method of the int type (yes - primitive types are also full-blown types, and have methods and properties).
    This is how it works:
    int result;
    bool success = int.TryParse(someString, out result);
    So, the 1st parameter is the string you want to convert; the 2nd parameter is an output parameter, as indicated by the out keyword - this is where the result of the conversion will be stored.
    The method returns true if the conversion was successful, and false if not - you can check this, and take appropriate action if the input is invalid (like ask the user to try again, or just use a default value).

    This is how you should use it:
    Code:
                int result;
                if (int.TryParse(input, out result))
                {
                    // OK. 
                    someVariable = result;  // for example myGame.userHigh = result;
                }
                else
                {
                    // please try again
                }
    Or alternatively, in some other variation, like:
    Code:
            int result;
            while(!int.TryParse(input, out result))  // while unsucessfull
            {
                // please try again
            }
            
            // OK. 
            someVariable = result;  // for example myGame.userHigh = result;

    This next bit is important - you don't want to exit your app with:
    Environment.Exit(1);

    Your program should be allowed to complete normally - by reaching the end of the Main() method (once all the loops finish). Besides, passing a nonzero argument to the Environment.Exit() method tells the operating system that the program was ended because of an error!

    Basically, you need to setup your application so that, once certain conditions are met, the loop condition will evaluate to false, and the loop will end - enabling the application to eventually reach the end of the Main() method and exit the way it's supposed to. To this end, I recommend, among other things, using Boolean variables for your loop conditions, instead of strings. For example, instead of:
    Code:
                string userChoice = "";
                while (userChoice == "")
                {
                    // ...
                }
    better use:
    Code:
                bool showMainMenu = true;
                while (showMainMenu)
                {
                    // ...
                }
    And then:
    Code:
                    //...
                    else if (userChoice == "3") // Exit game
                    {
                        //...
                        showMainMenu = false;   // it will exit on the next iteration
                    }
                    //...
    To handle the complexity of some of the inner loops, the continue statement may prove handy. It's used in loops, and once reached, the rest of the code is simply skipped, and execution immediately jumps to the next iteration. For example, in a situation like this:
    Code:
    bool valid = myGame.SetUserGuess(userInputString);   // this is just some method to help with validation
    if (!valid)
    {
        Console.WriteLine("Invalid input. Please try again:");
        continue;   // skips the rest of the loop (this is the most inner loop, where the user is asked to guess the secret number)
    }
    
    // Now you can compare the input and the target number.
    // ...
    Speaking of the most inner loop, you should move the lines that ask the user to enter the limits of the range out of the loop (you need to ask the user only once).
    You should also use ReadLine() instead of Read() to get user input:
    userInputString = Console.ReadLine();

    BTW, the point of the game is for the computer to tell the player if the target number is lower or higher than the provided number, not just to say "wrong! (randomly) try again! hahaha!". This way, the player can use a strategy similar to binary search, to eventually guess the number relatively quickly.

    I also think that you should avoid using Thread.Sleep(). I think doing something like this is better:
    Code:
            private static void Pause()
            {
                Console.WriteLine("Press any key to continue.");
                Console.ReadKey(true);
            }
    The true simply means that the key press will be hidden (no text will be displayed in console).
    Add this method to the Program class, and call it from Main() where required.
    You can also use Console.Clear() to occasionally clear the screen.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured