TCP Games - Guess My Number
Guess My Number is a very simple game. It's played by only one player. The server will think of a number between 1 and 100 (included) and then ask the client to guess it. It will tell the client if their guess was too high or too low. Once the user guesses correctly the game will then tell the server to disconnect the player. Keep in mind the
Run() method is run in a separate thread. While the rest of the server is asynchronous and multithreaded, we're going to run stuff synchronously and single threaded here.
Like said before, it needs to implement the
IGame interface. At the top we store a pointer to the
TcpGamesServer that is running this game. This way we can access the server's methods to transmit
Packets. We simply call our game "Guess My Number," with the
Name property. And the
RequiredPlayers only is one. In our constructor we also initialize a random number generator.
AddPlayer() will only accept one player for the game. If another one is provided, we ignore them and return
DisconnectClient() is a notifying method. In case we have one and it's our player, then we need to disconnect them (thus also quitting the Game too).
Run() method will not start the game unless we have a player. If we do, we send them a
Packet containing the rules. Then we generate our number. In the main game loop we send the user a request for
ReceivePacket() might return a
null, we keep checking in a loop until we have one. Our Game has to check for disconnects since we're now handling the client. If is there is a graceful one we mark it. If we get a response to our
input request, we then check it. Based on the
input, we see if they were right or wrong and send them a
message based upon that. At the end of the main game loop we check for our disconnects (graceful or not).
Once the client has disconnected or guessed the right number, we exit the
Run() function. And then our game is over.