Thread: (urgent) Multiplayer Poker game using Socket Programming

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    12

    (urgent) Multiplayer Poker game using Socket Programming

    I have this Project in School we have to make a Multiplayer Poker game using Socket Programming.

    We were not taught enough to dive into multithreaded programming and I am no expert in studying. Programming is really my weakness but I need to finally pass this course and I am this problem away from passing. I repeated this course 2 times but I failed and this is my last chance of passing or else Ill be cut from my course.

    Will you please help me?

    details:

    1.2 Scope
    Glade/GTK
    Signals and Timers
    FileIO
    Sockets
    SQL Database

    2 Program Overview
    The MP will be a network-based, multiplayer card game (Pusoy Dos) program. There are basically two
    major software components of the program; the Game Server and the Game Clients. Your program is
    only responsible for the Game Client (the Player’s User Interface). The EEE13 faculty will provide the
    Game Server.
    Your program connects to the Game Server to get shuffled cards. It then displays the cards in the GUI
    to allow the player to select cards to play on his/her turn. The cards are validated by the Game
    Server, and if the card combination is valid and of higher rank than the previous player’s cards, the
    cards are accepted and the other player will be serviced. The game ends when a player has no cards
    left and is declared as a winner.

    3 General Requirements
    3.1 Development Environment
    The program must be developed under Linux O.S. The IDE or editor can be any of your choice.

    4.3 Fixing of Cards
    The player should be able to arrange the cards at any time of the game. You may choose any method
    to allow the user to arrange the cards (e.g. via Button Clicks or via Drag & Drop).
    4.4 First Player
    The player who gets the 3-of-Club card will be the first player to submit cards. However, unlike with
    MP1, the Game Server is the one who decides which player got the 3-of-Club by sending the client
    program the “Your Turn” message. Since the First Player cannot pass, the first player has unlimited
    time to play his/her turn.
    4.5 Ending a Turn
    There are two ways to end a turn. One is by clicking the “Submit” button, and the other one is when a
    timer runs out. If the Player clicks the Submit button, the program must send the cards to the Game
    Server. The server validates the cards if it is a valid card combination, and if the card combination is
    of higher rank than the recently submitted cards. If the cards are rejected by the Game Server, your
    client program should allow the player to change the cards until the timer runs out.
    When the timer expires, the Game Server will treat this as a “Pass” and the turn will proceed to the
    next player.
    A player may pass by clicking the “Submit” button without placing any cards on the “Current Turn”
    table. If all 3 consecutive players passed, then the last player will be given a chance to place a new
    set or combination of cards. In this case, this player cannot pass his turn and the timer is disabled.

    4.6 Declaring the Winner
    The first player that is able to deal all his cards (has no cards left) will be declared as the Winner.
    Unlike with MP1, the winner is being declared by the server thru a “Player Wins” message. The
    program must pop a window containing text congratulating the player. The program terminates after
    the winner clicks a button in that window.
    5 Server-Client Protocol
    The Game Server will be running in the UnPlug Server to host multiple game sessions or game rooms.
    The TCP/IP port number that will be used by default will be port 9034.

    5.2 Protocol Data Format
    The Protocol Data format will be in a form of a CSV (Comma Separated Values). The table below
    enumerates the Messages and its parameters.
    Message Data Format
    JoinGame joingame, player_name, room#
    StartGame startgame, player#
    InitialCards initialcards, count, cardcode, cardcode, cardcode...
    YourTurn yourturn, timeout_value
    DealCards dealcards, count, cardcode, cardcode, cardcode...
    DealCardsResponse dealcards_response, pass/fail
    Cards cards, player#, count, cardcode, cardcode, cardcode...
    DeclareWinner playerwins, player#
    5.2.1 Join Game
    This message is sent by the Pusoy Dos client to register a player to join a game identified by the
    room#.
    Parameter Description
    player_name String representing the player’s name. String must only contain
    alphanumeric characters, and must not contain any comma (,).
    This name will be registered in the Server’s database for retrieval of High
    Score list.
    room# An integer to uniquely identify a game. Only 4 players can join a game
    room in a single game. To ensure that no students will be able to destruct
    the testing of another student, the student number is recommended to be
    used as the room#.
    5.2.2 StartGame
    This message is sent by the Game Server to inform the clients the all 4 players have joined and the
    game can now start.
    Parameter Description
    player# A decimal value representing the assigned player number for the client.
    This player number should be displayed in the GUI.
    5.2.3 Initial Cards
    This message is sent by the Game Server to each client to provide the shuffled cards.
    Parameter Description
    count A decimal value indicating the number of cards in the message. This is
    always 13 for a 4-player Pusoy Dos.
    cardcode A string representation of a card. Card code convention will be
    value+suit.
    Ace = ‘a’, Jack = ‘j’, Queen = ‘q’, King = ‘k’
    Club = ‘c’, Spade = ‘s’, Heart = ‘h’, Diamond = ‘d’
    e.g. ah,2d,jc,3s represents Ace-of-Heart, Two-of-Diamond, Jack-of-Club,
    and Three-of-Spade.
    5.2.4 YourTurn
    This message is used by the Game Server to inform a Client on its turn.
    Parameter Description
    timeout_value A decimal value indicating the number of seconds that the Game Server
    will wait for the client program to submit valid cards. After this timeout
    value, the Game Server will assume that the Player passed.
    A timeout value of 0 means no timeout. This is usually set for the First
    Player or when all other 3 players passed.

    5.2.5 DealCards
    This message is used to submit cards to the Game Server. The Game Server validates the cards
    contained in this message and reply with a DealCardsResponse.
    Parameter Description
    count A decimal value indicating the number of cards in the message.
    cardcode A string representation of a card. See section 5.2.3 InitialCards table for
    details.
    5.2.6 DealCardsResponse
    This is a response to the DealCards message.
    Parameter Description
    pass/fail A string indicating if the cards submitted is accepted by the Game Server.
    If the response is “fail”, the Client program must return the cards to the
    Current Turn table. If the response is “pass”, the Client Program must
    place the cards into the Previous Turn table.
    5.2.7 Cards
    This message is broadcasted by the Game Server to other 3 players after a successful DealCards. It
    informs the other 3 players what cards the current player submitted.
    Parameter Description
    player# A decimal value indicating which player has submitted the cards.
    count A decimal value indicating the number of cards in the message.
    cardcode A string representation of a card. See section 5.2.3 InitialCards table for
    details.
    5.2.8 DeclareWinner
    This message is sent by the Game Server to all players to inform the players which player wins the
    game. When this message is received by the Client program, the client program must show a dialog
    box to congratulate or if the player is defeated.
    Parameter Description
    player# A decimal value indicating which player wins the game.



    I know this is a bit too much but Im really desperate for help now. I'm just knowledgeable about glade and some C functions but games like these I really don't succeed in.

    Please please someone help. I really really will appreciate ANY HELP.


    Thanks and more power.

  2. #2
    Registered User
    Join Date
    Oct 2009
    Posts
    5
    I don't know how much help you'll get just posting a homework assignment. People are willing to help out in a problem/bug you have, but not usually so willing to do your homework.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    In order to avoid just being a "homework do'er depot", the forum policy is that you show your work, and ask specific questions.

    We don't do entire homework assignments or projects, for people.

    Your assignment write up seems longer than most, so I'd say your chances of getting someone to do it for you, for free, is zip. If you really are completely lost on this, you might try Rent-A-Coder's site, and see if you can hire a programmer to help you.

    Other than that, try scouring Google and see if you can find some open source code that you can see how this type of programming code is done, and start studying up.

  4. #4
    Registered User
    Join Date
    Oct 2009
    Posts
    12
    okay then Ill start with my most basic problems. but how do I post a code here? are there specific techniques? I have a Machine Problem1 partly done.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    When you want to post code, use the "post reply" or "quote" buttons, not the "Quick Reply" window.

    Click on the # sign that you'll find just below the smilie's pull down list, in the header of that window. It will put up your needed code tags [/code][//code] (I've added one / extra so these will stay visibile).

    Then move your cursor right between the code tags, and hit enter. Paste your code right into that space, between the code tags. Because of the font type (fixed width - sort of), keep the line width of your code, down to about 60 char's.

    That way, everything stays visible without "breaking the tables", in excess width.

    You can also just highlight your code, and click on the # icon. The tags will automatically prefix and suffix your program.

  6. #6
    Registered User
    Join Date
    Oct 2009
    Posts
    12

    first off..

    first off i need to learn threads and i found this:

    Code:
    #include 
    
    void *print_message_function( void *ptr );
    
    int main()
    {
      GThread          *Thread1, *Thread2;
      char *message1 = "Thread 1";
      char *message2 = "Thread 2";
      GError           *err1 = NULL ;
      GError           *err2 = NULL ;
    
      if( !g_thread_supported() )
      {
         g_thread_init(NULL);
         gdk_threads_init();                   // Called to initialize internal mutex "gdk_threads_mutex".
         printf("g_thread supported\n");
      }
      else
      {
         printf("g_thread NOT supported\n");
      }
    
      if( (Thread1 = g_thread_create((GThreadFunc)print_message_function, (void *)message1, TRUE, &err1)) == NULL)
      {
         printf("Thread create failed: %s!!\n", err1->message );
         g_error_free ( err1 ) ;
      }
    
      if( (Thread2 = g_thread_create((GThreadFunc)print_message_function, (void *)message2, TRUE, &err2)) == NULL)
      {
         printf("Thread create failed: %s!!\n", err2->message );
         g_error_free ( err2 ) ;
      }
    
      g_thread_join(Thread1);
      g_thread_join(Thread2);
    
      return 0;
    }
    
    void *print_message_function( void *ptr )
    {
         char *message;
         g_usleep(1000000);
         message = (char *) ptr;
         printf("%s \n", message);
         g_usleep(1000000);
         printf("%s \n", message);
    }
    output is
    [prompt]$ gdk-thread-only
    g_thread supported
    Thread 1
    Thread 2
    Thread 1
    Thread 2

    I am thinking the output should be

    [prompt]$ gdk-thread-only
    g_thread supported
    Thread 1
    Thread 1
    Thread 2
    Thread 2

    and do i need to g_thread_create() every function i need in my main such as joingame, dealcards, etc?

  7. #7
    Registered User
    Join Date
    Oct 2009
    Posts
    12
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <unistd.h>
    
    tokenize(char string[])
    {
        char *string1;
        char value[10][20], j, i=0;
        string1 = (char *)strtok(string,", \n \t");
    i=0;
        while( string1 != NULL) {			
    	    strcpy(value[i],string1);			
                string1 = (char *)strtok(NULL,"\n , \t");
        i++;}
        for (j=0; j < i; j++)
    	printf("Component: %s\n", value[j]); 
    }
    
    int main(int argc, char *argv[])
    {
      char toser[100];
      char fromser[100];
      char tosercpy[100];
      char fromsercpy[100];
      char protocol[10][20];
      char protocolA[20];
      char *pch;
       char str[100];
    /*  while(1){
    	fgets(toser,sizeof(toser),stdin);
                protocol = strtok (toser,", ");
              while (pch != NULL)
              {
                strcpy(protocol, pch);
                pch = strtok (NULL, " ");
              }*/
    fgets(fromser,sizeof(fromser),stdin);
    tokenize(fromser);
    /*  if(strcmp(protocol,"JoinGame")==0){
    	printf("oo JoinGame nga\n");
      }
      if (strcmp(protocol,"StartGame,")==0){
    	printf("StartGame\n");
      }
      if(strcmp(protocol,"InitialCards,")==0){
    	printf("JoinGame\n");
      }
      if (strcmp(protocol,"YourTurn,")==0){
    	printf("YourTurn\n");
      }
      if(strcmp(protocol,"DealCards,")==0){
    	printf("DealCards\n");
      }
      if (strcmp(protocol,"DealCardsResponse")==0){
    	printf("DealCardsResponse\n");
      }
      if(strcmp(protocol,"Cards")==0){
    	printf("Cards\n");
      }
      if (strcmp(protocol,"DeclareWinner")==0){
    	printf("DeclareWinner\n");
      }
    }*/
     return 0;
    }
    how do i save to protocol[i++][20] the Components extracted/tokenized from tokenize()?

  8. #8
    Registered User
    Join Date
    Oct 2009
    Posts
    12

    third question

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <errno.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
      int sockfd;
      int port;
      char* server=argv[1];
      struct sockaddr_in servaddr;
      char toser[100];
      char fromser[100];
      char tosercpy[100];
      char fromsercpy[100];
      char protocol[20];
      char protocolA[20];
      if(argc<2){ 
    	printf("Syntax: ./pusoydos <--host server_ip> [--port port_number] [--version] \n");
    	return -EINVAL; 
      }
      if (argc==2){
    	port=9034;
      }
      else if (argc==3){
    	port=atoi(argv[2]);
      }
      else if (argc == 4){
    
            showinfo();
    	return 0;
    
      }
    
      sockfd = socket(PF_INET,SOCK_STREAM,0);
      if(sockfd<0) {
    	perror("socket");
    	return -EIO;
      }
    
      bzero(&servaddr, sizeof(servaddr));
      servaddr.sin_family = AF_INET;
      servaddr.sin_port = htons(port);
      inet_pton(AF_INET,server,&servaddr.sin_addr);
    
      if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0){
    	perror("connect");
    	close(sockfd);
    	return -EIO;
      }
      while(1){
    	memset(fromser, 0, sizeof(fromser));
    	fgets(toser,sizeof(toser),stdin);
    	send(sockfd,toser,strlen(toser),0);
    	recv(sockfd,fromser,sizeof(fromser),0); 
    	strcpy(tosercpy, toser);
    	strcpy(fromsercpy,fromser);
    	char *protocol;
    	char *protocolyou;
    	protocol = strtok (fromsercpy,", ");
    	protocolyou = strtok(tosercpy,", ");
      if(strcmp(protocolyou,"joingame")==0){
    /*don;t know what the content will be*/
      }
      if (strcmp(protocol,"startgame")==0){/*This message is sent by the Game Server to inform the clients that all 4 players have joined and the
    game can now start.*/
    	printf("StartGame\n");
    	int playno;
      }
      if(strcmp(protocol,"initialcards")==0){
    	/*This message is sent by the Game Server to each client to provide the shuffled cards.*/
    	int count=protocol[1];
    	int cardcode[count];
    	int ctr;
    	for (ctr=0; ctr<count; ct++){
    	  strcpy(cardcode[ctr],protocol[ctr+2]);
    	}
    /*I plan to put the GUI creation part here, after receiving the cards*/
      }
      if (strcmp(protocol,"yourturn")==0){
    	printf("YourTurn\n");
    	int timeout=protocol[1];
    
      }
      if(strcmp(protocolyou,"dealcards")==0){/*protocolyou is not actually from fgets but from a button-click signal. How do I do that(?)*/
    	printf("DealCards\n");
    	protocolyou="dealcards";
    	int cardct, ct;
    	for (ct=0; ct<cardct; ct++){
    	strcat(protocolyou, storedcard[ct]);
      	}
      }
      if (strcmp(protocol,"dealcards_response")==0){
    	printf("DealCardsResponse\n");
    	if (protocol[1]==pass){
    	}
    	if (protocol[2]==fail){
    	/*buttons submitted reappear*/
    	}
      }
      if(strcmp(protocol,"cards")==0){
    	printf("Cards\n");
      }
      if (strcmp(protocol,"playerwins")==0){
    	printf("DeclareWinner\n");
      }
    }
      close(sockfd);
      return 0;
    }
    the code for sockets there is from the last exercise we had. but they said that threading should be used for this. it's like fork according to them. that is so that we can run simultaneous stuff.

    thank you very much for your patience Mr.Adak and friends.

  9. #9
    Registered User jdragyn's Avatar
    Join Date
    Sep 2009
    Posts
    96
    Quote Originally Posted by Whilst View Post
    I am thinking the output should be

    [prompt]$ gdk-thread-only
    g_thread supported
    Thread 1
    Thread 1
    Thread 2
    Thread 2
    Not necessarily. It is possible that the order of execution could end up printing

    Thread 2
    Thread 1
    Thread 2
    Thread 1

    or any other arbitrary combination. When you create a new thread, it begins execution independant of the rest of your program and any other threads you create. It seems likely to me that Thread 1 will execute and print its message first because you are creating it first, but that is not a guarantee.
    Quote Originally Posted by Whilst View Post
    and do i need to g_thread_create() every function i need in my main such as joingame, dealcards, etc?
    That would be overkill, not to mention a nightmare.

    I've looked over your assignment a few times now, and I don't see anywhere in the assignment itself that requires multi-threading, only in your assessment of what you need to do. You can write this program without multi-threading. Of course you COULD use threads, but I don't see this as a situation where the benefits of multi-threading would outweigh the design complexity. It does appear that you've not shown us everything about the assignment; in particular, 1.1 is missing, 4.1 and 4.2 are missing, 5.1 is missing... Based on what you DID post however:

    You only need to worry about a single player with your program. Several instances of your program will be running, one per player and presumably each on a separate computer. The Game Server (which you are not writing) will accept the connections for each player and then "focus its attention" on one player at a time in a round-robin manner. If you pretend that all the other players are connecting with some other client (which may actually be what happens when the instructor tests the programs), then you only worry about when the Game Server focuses attention on YOUR client.

  10. #10
    Registered User
    Join Date
    Oct 2009
    Posts
    12
    Quote Originally Posted by jdragyn View Post
    Not necessarily. It is possible that the order of execution could end up printing

    It does appear that you've not shown us everything about the assignment; in particular, 1.1 is missing, 4.1 and 4.2 are missing, 5.1 is missing... Based on what you DID post however:
    You are right. Those are unimportant information such as compiling issues, non-functional requirements etc.

    Quote Originally Posted by jdragyn View Post
    You only need to worry about a single player with your program. Several instances of your program will be running, one per player and presumably each on a separate computer. The Game Server (which you are not writing) will accept the connections for each player and then "focus its attention" on one player at a time in a round-robin manner. If you pretend that all the other players are connecting with some other client (which may actually be what happens when the instructor tests the programs), then you only worry about when the Game Server focuses attention on YOUR client.
    That's what I was thinking from day 1 I received this work. So, I will just put things (sending and receiving) in the while loop? will it automatically process something (from any of the if-statements) once it sends/receives anything?

    Oh man, I think I want to have this done now. Thanks for the encouragement.

  11. #11
    Registered User
    Join Date
    Oct 2009
    Posts
    12
    I'd appreciate if you take a look on my previous questions too, like strcopy()ing tokenized components to a 2d-array and the comments I've got from my template of code.

  12. #12
    Registered User jdragyn's Avatar
    Join Date
    Sep 2009
    Posts
    96
    Quote Originally Posted by Whilst View Post
    how do i save to protocol[i++][20] the Components extracted/tokenized from tokenize()?
    You could use strtok(). You should also declare tokenize() to return something, and you could use this return value to return the number of tokens extracted from the fromser buffer to the protocol[][] array. You would want to also pass the protocol array to tokenize, as well as how big the protocol array is (to prevent tokenize() from trying to add more to the array than it can handle). And with the InitialCards message, the directions say that it will send the "initialcards" token, the count token and then 13 cards, so protocol would need to hold at least 15 tokens but you have it declared to hold only 10.

    The easiest way to use strtok() with your protocol array would be to change protocol from char protocol[10][20]; to char* protocol[MAX_TOKENS]; This would allow you to directly assign the result of strtok() to each element of protocol. Notice I did not put any numbers in the declaration either. You can #define MAX_TOKENS 15 (note no semi-colon) and then if you find you need more than 15 you can change this later. Then you can also use MAX_TOKENS anywhere you need to make sure you don't run off the end of the protocol array instead of using magic numbers.

  13. #13
    Registered User
    Join Date
    Oct 2009
    Posts
    12
    Thanks for the tip on the MAX TOKEN, and sorry for the insufficient array size indication. just shows how poor a programmer I am.

    Quote Originally Posted by jdragyn View Post
    You should also declare tokenize() to return something, and you could use this return value to return the number of tokens extracted from the fromser buffer to the protocol[][] array.
    That's exactly where I'm lost. How do I write return value[i++] without exiting the function yet until it's completely tokenized?

  14. #14
    Registered User jdragyn's Avatar
    Join Date
    Sep 2009
    Posts
    96
    Code:
    #include <string.h>
    
    #define MAX_TOKENS 15
    
    int tokenize(char* message, char* tokens[], int size_of_tokens_array) {
      /* using strtok, loop until strtok returns NULL to indicate
         there are no more tokens in message */
    
      /* in each iteration of the loop... */
    
         /* assign the result of strtok to the current element of
            tokens[] (starting with the first element) */
    
         /* after assigning the result of strtok, advance a counter
            to keep track of how many tokens have been extracted */
    
      /* once the loop exits (for the above reason) return the counter
         so the caller of tokenize() knows how many tokens they can use */
    }
    
    int main() {
      int num_tokens;
      char* protocol[MAX_TOKENS] = { 0 };
      char* fromser;
    
      /* get the message from the server and store in fromser */
    
      num_tokens = tokenize(fromser, protocol, MAX_TOKENS);
    
      /* now process your tokens which will all be stored in the protocol
         array, and num_tokens will tell you how many are in the array */
    
      return 0;
    }
    As you see from my example, in main you pass protocol to tokenize() and when tokenize returns all of the tokens are extracted into the elements of protocol. You aren't returning any value[i++] or anything like that, you are returning a single integer that represents how many tokens the tokenize function extracted.

    I am not going to write the actual code for you, nor should you expect anyone else to do so. As a programmer, YOU have to figure this stuff out. YOU need to work out what a function needs to do and how it should do it. If you aren't sure, then you should work it out some other way (on paper, in pseudo-code, in comments as I have done, etc.). Figure out what you want your program to do before you ever write a single line of code. The C code is a translation for the computer of what YOU want to happen during the run of your program.

    For having been through this programming course twice already and asking for help so you don't flunk out a third time, I expect you to figure out how the tokenize function should work on your own. "just shows how poor a programmer I am" is not an excuse, it is being lazy. If you want to write programs you have to put forth the effort, not put forth excuses.

    Now, I have taken a simple function that you are trying to figure out and given you more than what you should need to write it. If you can't figure it out on your own then perhaps there is a reason you've had to take this course multiple times.

  15. #15
    Registered User
    Join Date
    Oct 2009
    Posts
    12
    i got a hint for the project today saying I need to have a receiving() function threaded so it will refresh things up everytime the program receives something. would that make sense?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Making a Poker Game
    By krazyxazn in forum C Programming
    Replies: 4
    Last Post: 04-07-2009, 06:45 PM
  2. 2D Game project requires extra C++ programmers, new or experienced
    By drallstars in forum Projects and Job Recruitment
    Replies: 2
    Last Post: 05-16-2007, 10:46 AM
  3. C Programming 2d Array Question
    By jeev2005 in forum C Programming
    Replies: 3
    Last Post: 04-26-2006, 03:18 PM
  4. craps game & dice game..
    By cgurl05 in forum C Programming
    Replies: 3
    Last Post: 03-25-2006, 07:58 PM
  5. beach bar (sims type game)
    By DrKillPatient in forum Game Programming
    Replies: 1
    Last Post: 03-06-2006, 01:32 PM