[Tux4kids-commits] r1163 - tuxmath/branches/lan/src

akash gangil gangil-guest at alioth.debian.org
Wed Jul 8 22:56:51 UTC 2009


Author: gangil-guest
Date: 2009-07-08 22:56:51 +0000 (Wed, 08 Jul 2009)
New Revision: 1163

Modified:
   tuxmath/branches/lan/src/game.c
   tuxmath/branches/lan/src/highscore.c
   tuxmath/branches/lan/src/mathcards.c
   tuxmath/branches/lan/src/mathcards.h
   tuxmath/branches/lan/src/network.c
   tuxmath/branches/lan/src/network.h
   tuxmath/branches/lan/src/setup.c
   tuxmath/branches/lan/src/titlescreen.c
Log:
start server before game now , else you will hang up , anyways it will hang up eventually for now, trying to get single player into the server scenario

Modified: tuxmath/branches/lan/src/game.c
===================================================================
--- tuxmath/branches/lan/src/game.c	2009-07-08 21:49:52 UTC (rev 1162)
+++ tuxmath/branches/lan/src/game.c	2009-07-08 22:56:51 UTC (rev 1163)
@@ -17,7 +17,8 @@
   Revised by David Bruce, Tim Holy and others
   2005-2007
 */
-
+#define DEFAULT_PORT 4779
+#define TUXMATH_DEBUG
 /* put this first so we get <config.h> and <gettext.h> immediately: */
 #include "tuxmath.h"
 
@@ -31,6 +32,7 @@
 #endif
 #include "SDL_image.h"
 
+#include "transtruct.h"
 #include "game.h"
 #include "fileops.h"
 #include "setup.h"
@@ -149,7 +151,7 @@
 static void game_handle_answer(void);
 static void game_countdown(void);
 static void game_handle_tux(void);
-static void game_handle_comets(void);
+static void game_handle_comets(char *,char *);
 static void game_handle_cities(void);
 static void game_handle_penguins(void);
 static void game_handle_steam(void);
@@ -173,7 +175,7 @@
 static void draw_console_image(int i);
 
 static void reset_level(void);
-static int add_comet(void);
+static int add_comet(char *);
 static void add_score(int inc);
 static void reset_comets(void);
 
@@ -186,17 +188,47 @@
 static void game_recalc_positions(void);
 
 void putpixel(SDL_Surface* surface, int x, int y, Uint32 pixel);
+void seperate_commmand_and_buf(char *,char *);
 
 #ifdef TUXMATH_DEBUG
 static void print_exit_conditions(void);
 static void print_status(void);
 #endif
 
+
+void seperate_commmand_and_buf(char command[NET_BUF_LEN],char buf[NET_BUF_LEN])
+{
+  int i;
+  /* Copy the command name out of the tab-delimited buffer: */
+  for (i = 0;
+  buf[i] != '\0' && buf[i] != '\t' && i < NET_BUF_LEN;
+                                      i++)
+  {
+    command[i] = buf[i];
+  }
+  command[i] = '\0';
+
+//#ifdef LAN_DEBUG
+//  printf("buf is %s\n", buf);
+//  printf("command is %s\n", command);
+//#endif
+
+}
+
 /* --- MAIN GAME FUNCTION!!! --- */
 
 
 int game(void)
 {
+  /*connecting to the server*/
+  if(!setup_net("localhost",DEFAULT_PORT))
+  {
+    printf("Unable to connect to the server\n");
+    game_cleanup();
+    exit(1);
+  }        
+
+
   Uint32 last_time, now_time;
 
 #ifdef TUXMATH_DEBUG
@@ -225,12 +257,16 @@
     game_cleanup();
     return GAME_OVER_OTHER;
   }
+ 
+ 
 
-
-
   /* --- MAIN GAME LOOP: --- */
   do
   {
+    char buf[NET_BUF_LEN];
+ 
+    char command[NET_BUF_LEN];
+    
     /* reset or increment various things with each loop: */
     frame++;
     last_time = SDL_GetTicks();
@@ -242,22 +278,26 @@
       laser.alive--;
     }
 
+    check_messages(buf);
+    seperate_commmand_and_buf(command,buf);
+
     /* Most code now in smaller functions: */
     game_handle_user_events();
     game_handle_demo();
     game_handle_answer();
     game_countdown();
     game_handle_tux();
-    game_handle_comets();
+    game_handle_comets(command,buf);
     game_handle_cities();
     game_handle_penguins();
     game_handle_steam();
     game_handle_extra_life();
     game_draw();
     /* figure out if we should leave loop: */
-    game_status = check_exit_conditions();
+//    game_status = check_exit_conditions();               //would have to work on these , as they follow question linked list method
+  
+ 
 
-
     /* If we're in "PAUSE" mode, pause! */
     if (paused)
     {
@@ -496,13 +536,17 @@
   /* to use MC_StartUsingWrongs() */
   /* NOTE MC_StartGame() will return 0 if the list length is zero due */
   /* (for example) to all math operations being deselected */
-  if (!MC_StartGame())
-  {
-    tmdprintf("\nMC_StartGame() failed!");
-    fprintf(stderr, "\nMC_StartGame() failed!");
-    return 0;
-  }
+//  if (!MC_StartGame())
+//  {
+//    tmdprintf("\nMC_StartGame() failed!");
+//    fprintf(stderr, "\nMC_StartGame() failed!");
+//    return 0;
+//  }
 
+   /*To function for the above 5 comments*/
+   say_to_server("START_GAME");
+
+
   /* Allocate memory */
   comets = NULL;  // set in case allocation fails partway through
   cities = NULL;
@@ -659,6 +703,8 @@
 
 void game_cleanup(void)
 {
+  
+  cleanup_client();
   /* Free background: */
   if (bkgd != NULL)
   {
@@ -874,7 +920,7 @@
   game_handle_user_events();
   game_handle_answer();
   game_handle_tux();
-  game_handle_comets();
+  game_handle_comets(NULL,NULL);
   game_handle_cities();
   game_handle_penguins();
   game_handle_steam();
@@ -1153,7 +1199,7 @@
   /* If there was an comet with this answer, destroy it! */
   if (lowest != -1)  /* -1 means no comet had this answer */
   {
-    MC_AnsweredCorrectly(&(comets[lowest].flashcard));
+    LAN_AnsweredCorrectly(&(comets[lowest].flashcard));
 
     /* Store the time the question was present on screen (do this */
     /* in a way that avoids storing it if the time wrapped around */
@@ -1301,7 +1347,7 @@
 
 //FIXME might be simpler to store vertical position (and speed) in terms of time
 //rather than absolute position, and determine the latter in game_draw_comets()
-void game_handle_comets(void)
+void game_handle_comets(char command[NET_BUF_LEN],char buf[NET_BUF_LEN])
 {
   /* Handle comets. Since the comets also are the things that trigger
      changes in the cities, we set some flags in them, too. */
@@ -1441,10 +1487,17 @@
     {
       if ((rand() % 2) == 0 || num_comets_alive == 0)
       {
-        if (add_comet())
-        {
-          num_attackers--;
-        }
+         while(strncmp(command,"SEND_QUESTION",strlen("SEND_QUESTION"))!=0)
+         {
+          check_messages(buf);
+          seperate_commmand_and_buf(command,buf);
+         }
+          if (add_comet(buf))
+          {
+            num_attackers--;
+          }
+        
+        
       }
     }
     else
@@ -2224,6 +2277,7 @@
         user_quit_received != GAME_OVER_CHEATER)
     {
     	 tmdprintf("Unexpected value %d for user_quit_received\n", user_quit_received);
+          printf("I am here!!!!!!");
     	 return GAME_OVER_OTHER;
     }
     return user_quit_received;    
@@ -2240,31 +2294,48 @@
   }
 
   /* determine if game won (i.e. all questions in mission answered correctly): */
-  if (MC_MissionAccomplished())
-  {
-    tmdprintf("Mission accomplished!\n");
-    return GAME_OVER_WON;
-  }
+//  if (MC_MissionAccomplished())
+//  {
+//    tmdprintf("Mission accomplished!\n");
+//    return GAME_OVER_WON;
+//  }
 
+    if(evaluate("MISSION_ACCOMPLISHED"))
+    {
+      tmdprintf("Mission accomplished!\n");
+      return GAME_OVER_WON;
+    } 
+  
+    printf("this is the value of mission accomplished... %d ...\n",evaluate("MISSION_ACCOMPLISHED"));
+
+
   /* Could have situation where mathcards doesn't have more questions */
   /* even though not all questions answered correctly:                */
-  if (!MC_TotalQuestionsLeft())
-  {
-    return GAME_OVER_OTHER;
-  }
+//  if (!MC_TotalQuestionsLeft())
+//  {
+//    return GAME_OVER_OTHER;
+//  }
 
+    if(!evaluate("TOTAL_QUESTIONS_LEFT"))
+    {
+     return GAME_OVER_OTHER;
+    }
+
   /* Need to get out if no comets alive and MathCards has no questions left in list, */
   /* even though MathCards thinks there are still questions "in play".  */
   /* This SHOULD NOT HAPPEN and means we have a bug somewhere. */
-  if (!MC_ListQuestionsLeft() && !num_comets_alive)
-  {
-    #ifdef TUXMATH_DEBUG
-    printf("\nListQuestionsLeft() = %d", MC_ListQuestionsLeft());
-    printf("\nnum_comets_alive = %d", num_comets_alive);
-    #endif
-    return GAME_OVER_ERROR;
-  }
+//  if (!MC_ListQuestionsLeft() && !num_comets_alive)
+//  {
+//    #ifdef TUXMATH_DEBUG
+//    printf("\nListQuestionsLeft() = %d", MC_ListQuestionsLeft());
+//    printf("\nnum_comets_alive = %d", num_comets_alive);
+//    #endif
+//    return GAME_OVER_ERROR;
+//  }
+   
+   
 
+
   /* If using demo mode, see if counter has run out: */
   if (Opts_DemoMode())
   {
@@ -2496,7 +2567,7 @@
 
 
 /* Add a comet to the game (if there's room): */
-int add_comet(void)
+int add_comet(char buf[NET_BUF_LEN])
 {
   static int prev_city = -1;
   int i, found;
@@ -2533,26 +2604,22 @@
 
   /* Get math question for new comet - the following function fills in */
   /* the flashcard struct that is part of the comet struct:            */
-//  if(n==1)
-//    {
-     if (!MC_NextQuestion(&(comets[found].flashcard)))
-     {
-      /* no more questions available - cannot create comet.  */
-      return 0;
-     }
-/*     if(!SendQuestion(&(comets[found].flashcard)))
-     {
-      printf("Unable to send Question\n");
-     }
-    }
+//     if (!MC_NextQuestion(&(comets[found].flashcard)))
+//     {
+//      /* no more questions available - cannot create comet.  */
+//      return 0;
+//     }
 
-  if(n==0)
-   { 
-     SDL_Delay(5000);
-     if(!ReceiveQuestion(&(comets[found].flashcard)))
-     printf("unable to recv question\n");
-    }
-*/
+ /*Server replacement for the above 5 comments*/
+   say_to_server("NEXT_QUESTION");
+   printf("buf is %s\n",buf);
+   if(!Make_Flashcard(buf, &(comets[found].flashcard)))
+   {
+     return 0;
+   }
+
+
+
   /* If we make it to here, create a new comet!                  */
 
   comets[found].answer = comets[found].flashcard.answer;

Modified: tuxmath/branches/lan/src/highscore.c
===================================================================
--- tuxmath/branches/lan/src/highscore.c	2009-07-08 21:49:52 UTC (rev 1162)
+++ tuxmath/branches/lan/src/highscore.c	2009-07-08 22:56:51 UTC (rev 1163)
@@ -19,9 +19,9 @@
 #include "options.h"
 #include "SDL_extras.h"
 #include "convert_utf.h"
-#include "network.h"
 
 
+
 typedef struct high_score_entry {
   int score;
   char name[HIGH_SCORE_NAME_LENGTH];

Modified: tuxmath/branches/lan/src/mathcards.c
===================================================================
--- tuxmath/branches/lan/src/mathcards.c	2009-07-08 21:49:52 UTC (rev 1162)
+++ tuxmath/branches/lan/src/mathcards.c	2009-07-08 22:56:51 UTC (rev 1163)
@@ -22,9 +22,10 @@
 #include <math.h>
 #include <time.h>
 
+
+#include "transtruct.h"
 #include "mathcards.h"
 
-
 /* extern'd constants */
 
 const char* const MC_OPTION_TEXT[NOPTS+1] = {
@@ -184,6 +185,7 @@
 MC_Options* math_opts = 0;
 MC_MathQuestion* question_list = 0;
 MC_MathQuestion* wrong_quests = 0;
+MC_MathQuestion* active_quests = 0;
 MC_MathQuestion* next_wrong_quest = 0;
 int initialized = 0;
 int quest_list_length = 0;
@@ -192,15 +194,17 @@
 int questions_pending = 0;
 int unanswered = 0;
 int starting_length = 0;
+//NOTE these are no longer used:
 int max_formula_size = 0; //max length in chars of a flashcard's formula
 int max_answer_size = 0; //and of its answer
 
 /* For keeping track of timing data */
+/*FIXME do we really need any of these? */
 float* time_per_question_list = NULL;
 int length_time_per_question_list = 0;
 int length_alloc_time_per_question_list = 0;
 
-const MC_FlashCard DEFAULT_CARD = {NULL,NULL,0,0}; //empty card to signal error
+const MC_FlashCard DEFAULT_CARD = {0,0,0,0}; //empty card to signal error
 
 /* "private" function prototypes:                        */
 /*                                                       */
@@ -283,8 +287,7 @@
   /* bail out if no struct */
   if (!math_opts)
   {
-
-    mcdprintf("\nError: math_opts null or invalid");
+    mcdprintf("\nError: malloc couldn't allocate math_opts for some reason\n");
     mcdprintf("\nLeaving MC_Initialize()\n");
 
     fprintf(stderr, "\nUnable to initialize math_options");
@@ -294,7 +297,7 @@
   /* set defaults */
   for (i = 0; i < NOPTS; ++i)
     {
-    math_opts->iopts[i] = MC_DEFAULTS[i];
+      math_opts->iopts[i] = MC_DEFAULTS[i];
     }
 
   /* if no negatives to be used, reset any negatives to 0 */
@@ -350,7 +353,9 @@
   question_list = NULL;
   delete_list(wrong_quests);
   wrong_quests = NULL;
-
+  delete_list(active_quests);
+  active_quests = NULL;
+  
   /* clear the time list */
   if (time_per_question_list != NULL) {
     free(time_per_question_list);
@@ -359,6 +364,8 @@
     length_alloc_time_per_question_list = 0;
   }
 
+  //NOTE this is going away - complicates code too much to calculate this to
+  //save a few bytes rather than making the string size constant
   /* determine how much space needed for strings, based on user options */
   max_formula_size = MC_GetOpt(MAX_FORMULA_NUMS)
                    * (log10i(MC_GLOBAL_MAX) + 4) //sign/operator/spaces
@@ -367,24 +374,14 @@
 
   mcdprintf("max answer, formula size: %d, %d\n",
             max_answer_size, max_formula_size);
-  /* set up new list with pointer to top: */
-// if(n==1)                             				//if selects server , n==1 from titlescreen.c 
-//  { 
-   question_list = generate_list();
 
-   next_wrong_quest = 0;
-   /* initialize counters for new game: */
-   quest_list_length = list_length(question_list);
+  question_list = generate_list();
+
+  next_wrong_quest = 0;
+  /* initialize counters for new game: */
+  quest_list_length = list_length(question_list);
   
-//   SendQuestionList(question_list,quest_list_length);
-//  } 
-  
-//if(n==0)							//if selects client , n==0 from titlescreen.c
-//{
-//   next_wrong_quest = 0;
-//   ReceiveQuestionList(question_list,quest_list_length);
- 
-//}
+
   /* Note: the distinction between quest_list_length and  */
   /* unanswered is that the latter includes questions     */
   /* that are currently "in play" by the user interface - */
@@ -439,7 +436,8 @@
 
     /* initialize lists for new game: */
     delete_list(question_list);
-    if(!randomize_list(&wrong_quests)) {
+    if(!randomize_list(&wrong_quests))
+    {
       fprintf(stderr, "Error during randomization of wrong_quests!\n");
       /* Punt on trying wrong question list, just run normal game */
       return MC_StartGame();
@@ -447,6 +445,8 @@
     question_list = wrong_quests;
     wrong_quests = 0;
     next_wrong_quest = 0;
+    delete_list(active_quests);
+    active_quests = 0;
    /* initialize counters for new game: */
     quest_list_length = list_length(question_list);
     unanswered = starting_length = quest_list_length;
@@ -473,57 +473,60 @@
 }
 
 
-/*  MC_NextQuestion() takes a pointer to an allocated     */
-/*  MC_MathQuestion struct and fills in the fields for    */
-/*  use by the user interface program. It basically is    */
-/*  like taking the next flashcard from the pile. The     */
-/*  node containing the question is removed from the list.*/
-/*  Returns 1 if question found, 0 if list empty/invalid  */
-/*  or if argument pointer is invalid.                    */
-int MC_NextQuestion(MC_FlashCard* fc)
-{
-  mcdprintf("\nEntering MC_NextQuestion()\n");
+/*  MC_NextQuestion() takes a pointer to an allocated      */
+/*  MC_MathQuestion struct and fills in the fields for     */
+/*  use by the user interface program. It basically is     */
+/*  like taking the next flashcard from the pile. The      */
+/*  node containing the question is removed from the list. */
+/*  Returns 1 if question found, 0 if list empty/invalid   */
+/*  or if argument pointer is invalid.                     */
+//int MC_NextQuestion(MC_FlashCard* fc)
+//{
+//  mcdprintf("\nEntering MC_NextQuestion()\n");
 
   /* (so we can free the node after removed from list:) */
-  MC_MathQuestion* ptr;
-  ptr = question_list;
+//  MC_MathQuestion* ptr;
+//  ptr = question_list;
 
-  if (!fc )
-  {
-    fprintf(stderr, "\nNull MC_FlashCard* argument!\n");
-    mcdprintf("\nLeaving MC_NextQuestion()\n");
-    return 0;
-  }
+//  if (!fc )
+//  {
+//    fprintf(stderr, "\nNull MC_FlashCard* argument!\n");
+//    mcdprintf("\nLeaving MC_NextQuestion()\n");
+//    return 0;
+//  }
 
-  if (!question_list ||
+//  if (!question_list ||
 /*      !next_question || */
-      !list_length(question_list) )
-  {
-    mcdprintf("\nquestion_list invalid or empty");
-    mcdprintf("\nLeaving MC_NextQuestion()\n");
+//      !list_length(question_list) )
+//  {
+//    mcdprintf("\nquestion_list invalid or empty");
+//    mcdprintf("\nLeaving MC_NextQuestion()\n");
 
-    return 0;
-  }
+//    return 0;
+//  }
 
   /* 'draw' - copy over the first question */
-  copy_card(&question_list->card, fc);
+//  copy_card(&question_list->card, fc);
  
-  /* 'discard' - take first question node out of list and free it */
-  question_list = remove_node(question_list, question_list);
-  free_node(ptr);
-  quest_list_length--;
-  questions_pending++;
+  /* take first question node out of list and move it into active_quests list: */
+//  question_list = remove_node(question_list, question_list);
+//  free_node(ptr);
+//  quest_list_length--;
+//  questions_pending++;
+//  append_node(active_quests, ptr);
 
-  #ifdef MC_DEBUG
-  printf("\nnext question is:");
-  print_card(*fc);
-  print_counters();
-  printf("\n\nLeaving MC_NextQuestion()\n");
-  #endif
+//  #ifdef MC_DEBUG
+//  printf("\nnext question is:");
+//  print_card(*fc);
+//  print_counters();
+//  printf("\n\nLeaving MC_NextQuestion()\n");
+//  #endif
 
-  return 1;
-}
+//  return 1;
+//}
 
+
+
 /*  MC_AnsweredCorrectly() is how the user interface      */
 /*  tells MathCards that the question has been answered   */
 /*  correctly. Returns 1 if no errors.                    */
@@ -546,6 +549,7 @@
   print_card(*fc);
   #endif
 
+  //FIXME we need to take the question out of the active_quests list
   answered_correctly++;
   questions_pending--;
 
@@ -580,6 +584,11 @@
   return 1;
 }
 
+int MC_AnsweredCorrectly_id(int id)
+{
+  return 1;
+}
+
 /*  MC_NotAnsweredCorrectly() is how the user interface    */
 /*  tells MathCards that the player failed to answer the  */
 /*  question correctly. Returns 1 if no errors.           */
@@ -1163,6 +1172,7 @@
   }
 }
 
+
 void print_vect_list(FILE* fp, MC_MathQuestion** vect, int length)
 {
   if (!vect)
@@ -1179,11 +1189,14 @@
   mcdprintf("Leaving print_vect_list()\n");
 }
 
+
+
 #ifdef MC_DEBUG
 void print_card(MC_FlashCard card)
 {
   printf("\nprint_card():");
-  printf("formula_string = %s\nanswer_string = %s\ndifficulty = %d\n\n",
+  printf("question_id=%d\nformula_string = %s\nanswer_string = %s\ndifficulty = %d\n\n",
+         card.question_id,
          card.formula_string,
          card.answer_string,
          card.difficulty);
@@ -1226,6 +1239,9 @@
 // }
 #endif
 
+
+
+
 int list_length(MC_MathQuestion* list)
 {
   int length = 0;
@@ -1446,11 +1462,12 @@
     return;
   mcdprintf("Copying '%s' to '%s', ", src->formula_string,dest->formula_string);
   mcdprintf("copying '%s' to '%s'\n", src->answer_string, dest->answer_string);
-  strncpy(dest->formula_string, src->formula_string, max_formula_size);
-  strncpy(dest->answer_string, src->answer_string, max_answer_size);
+  strncpy(dest->formula_string, src->formula_string, MC_FORMULA_LEN);
+  strncpy(dest->answer_string, src->answer_string, MC_ANSWER_LEN);
   mcdprintf("Card is: '%s', '%s'\n", dest->formula_string, dest->answer_string);
   dest->answer = src->answer;
   dest->difficulty = src->difficulty;
+  dest->question_id = src->question_id;
 }
 
 void free_node(MC_MathQuestion* mq) //no, not that freenode.
@@ -1490,9 +1507,11 @@
   int length;
   MC_ProblemType pt;
   MC_FlashCard ret;
+  static int generate_random_flashcard_id=0;
 
+  generate_random_flashcard_id+=1;
   mcdprintf("Entering generate_random_flashcard()\n");
-
+  mcdprintf("%d\n",generate_random_flashcard_id);
   do
     pt = rand() % MC_NUM_PTYPES;
   while ( (pt == MC_PT_TYPING && !MC_GetOpt(TYPING_PRACTICE_ALLOWED) ) ||
@@ -1509,10 +1528,11 @@
     ret = MC_AllocateFlashcard();
     num = rand() % (MC_GetOpt(MAX_TYPING_NUM)-MC_GetOpt(MIN_TYPING_NUM) + 1)
                   + MC_GetOpt(MIN_TYPING_NUM);
-    snprintf(ret.formula_string, max_formula_size, "%d", num);
-    snprintf(ret.answer_string, max_answer_size, "%d", num);
+    snprintf(ret.formula_string, MC_FORMULA_LEN, "%d", num);
+    snprintf(ret.answer_string, MC_ANSWER_LEN, "%d", num);
     ret.answer = num;
     ret.difficulty = 10;
+    ret.question_id=generate_random_flashcard_id;
   }
   else //if (pt == MC_PT_ARITHMETIC)
   {
@@ -1548,11 +1568,13 @@
   int r1 = 0;
   int r2 = 0;
   int ans = 0;
-  char tempstr[max_formula_size];
+  char tempstr[MC_FORMULA_LEN];
   MC_FlashCard ret;
   MC_Operation op;
+  static int id = 0;
 
-  printf(".");
+  id += 1;
+  mcdprintf(".");
   if (length > MAX_FORMULA_NUMS)
     return DEFAULT_CARD;
   if (length <= 2)
@@ -1622,9 +1644,9 @@
 
 
     mcdprintf("Constructing answer_string\n");
-    snprintf(ret.answer_string, max_answer_size+1, "%d", ans);
+    snprintf(ret.answer_string, MC_ANSWER_LEN, "%d", ans);
     mcdprintf("Constructing formula_string\n");
-    snprintf(ret.formula_string, max_formula_size, "%d %c %d",
+    snprintf(ret.formula_string, MC_FORMULA_LEN, "%d %c %d",
              r1, operchars[op], r2);
     ret.answer = ans;
     ret.difficulty = op + 1;
@@ -1686,19 +1708,19 @@
     if (op == MC_OPER_SUB || op == MC_OPER_DIV || //noncommutative, append only
         rand() % 2)
     {
-      snprintf(tempstr, max_formula_size, "%s %c %d", //append
+      snprintf(tempstr, MC_FORMULA_LEN, "%s %c %d", //append
                ret.formula_string, operchars[op], r1);
-      strncpy(ret.formula_string, tempstr, max_formula_size);
+      strncpy(ret.formula_string, tempstr, MC_FORMULA_LEN);
     }
     else //we're prepending
     {
-      snprintf(tempstr, max_formula_size, "%d %c %s", //append
+      snprintf(tempstr, MC_FORMULA_LEN, "%d %c %s", //append
                r1, operchars[op], ret.formula_string);
-      strncpy(ret.formula_string, tempstr, max_formula_size);
+      strncpy(ret.formula_string, tempstr, MC_FORMULA_LEN);
     }
 
     //finally update the answer and score
-    snprintf(ret.answer_string, max_answer_size, "%d", ret.answer);
+    snprintf(ret.answer_string, MC_ANSWER_LEN, "%d", ret.answer);
     ret.difficulty += (length - 1) + op;
   }
   
@@ -1710,9 +1732,10 @@
     } while (!MC_GetOpt(FORMAT_ANSWER_LAST + format) && 
              !MC_GetOpt(FORMAT_ADD_ANSWER_LAST + op * 3 + format) );
    
-    strncat(ret.formula_string, " = ?", max_formula_size - strlen(ret.formula_string) );
+    strncat(ret.formula_string, " = ?", MC_FORMULA_LEN - strlen(ret.formula_string) );
     reformat_arithmetic(&ret, format );     
   }
+  ret.question_id=id;
   return ret;
 }
 
@@ -1728,12 +1751,16 @@
   MC_MathQuestion* end_of_list = NULL;
   MC_MathQuestion* tnode = NULL;
 
+#ifdef MC_DEBUG
   MC_PrintMathOptions(stdout, 0);
+#endif
+
   if (!(MC_GetOpt(ARITHMETIC_ALLOWED) ||
       MC_GetOpt(TYPING_PRACTICE_ALLOWED) ||
       MC_GetOpt(COMPARISON_ALLOWED) ) )
     return NULL;
 
+  //FIXME - remind me, why are we doing this??
   //randomize list length by a "bell curve" centered on average
   if (length && MC_GetOpt(VARY_LIST_LENGTH) )
   {
@@ -1806,7 +1833,7 @@
           tnode->card = generate_random_flashcard();
           list = insert_node(list, end_of_list, tnode);
           end_of_list = tnode;
-          mcdprintf("%d...", list_length(list) );
+//          mcdprintf("%d.", list_length(list) );
         }
       }
       else if (length < cl) //if too many questions, chop off tail end of list
@@ -1845,9 +1872,9 @@
 
 static int compare_card(const MC_FlashCard* a, const MC_FlashCard* b)
 {
-  if (strncmp(a->formula_string, b->formula_string, max_formula_size) )
+  if (strncmp(a->formula_string, b->formula_string, MC_FORMULA_LEN) )
     return 1;
-  if (strncmp(a->answer_string, b->answer_string, max_answer_size) )
+  if (strncmp(a->answer_string, b->answer_string, MC_ANSWER_LEN) )
     return 1;
   if (a->answer != b->answer);
     return 1;
@@ -1861,36 +1888,41 @@
 MC_FlashCard MC_AllocateFlashcard(void)
 {
   MC_FlashCard ret;
-  mcdprintf("Allocating %d + %d bytes for flashcard\n",
-            max_formula_size + 1, max_answer_size + 1);
-  ret.formula_string = malloc( (max_formula_size + 1) * sizeof(char));
-  ret.answer_string = malloc( (max_answer_size + 1) * sizeof(char));
-  if (!ret.formula_string || !ret.answer_string)
-    {
-    free(ret.formula_string);
-    free(ret.answer_string);
-    printf("Couldn't allocate space for a new flashcard!\n");
-    ret = DEFAULT_CARD;
-    }
+
+//NOTE strings now simply hard-coded to MC_FORMULA_LEN (= 40) and
+//MC_ANSWER_LEN (= 5) instead of tailoring them to save a few bytes - DSB
+//  mcdprintf("Allocating %d + %d bytes for flashcard\n",
+//            max_formula_size + 1, max_answer_size + 1);
+//  ret.formula_string = malloc( (max_formula_size + 1) * sizeof(char));
+//  ret.answer_string = malloc( (max_answer_size + 1) * sizeof(char));
+//   if (!ret.formula_string || !ret.answer_string)
+//     {
+//     free(ret.formula_string);
+//     free(ret.answer_string);
+//     printf("Couldn't allocate space for a new flashcard!\n");
+//     ret = DEFAULT_CARD;
+//     }
   return ret;
 }
 
+//Now a no-op - MC_FlashCard no longer has dynamically allocated strings
 void MC_FreeFlashcard(MC_FlashCard* fc)
 {
-  if (!fc)
-    return;
-//  mcdprintf("Freeing formula_string\n");
-  if (fc->formula_string)
-  {
-    free(fc->formula_string);
-    fc->formula_string = NULL;
-  }
-//  mcdprintf("Freeing answer_string\n");
-  if (fc->answer_string)
-  {
-    free(fc->answer_string);
-    fc->answer_string = NULL;
-  }
+  return;
+//   if (!fc)
+//     return;
+// //  mcdprintf("Freeing formula_string\n");
+//   if (fc->formula_string)
+//   {
+//     free(fc->formula_string);
+//     fc->formula_string = NULL;
+//   }
+// //  mcdprintf("Freeing answer_string\n");
+//   if (fc->answer_string)
+//   {
+//     free(fc->answer_string);
+//     fc->answer_string = NULL;
+//   }
 }
 
 unsigned int MC_MapTextToIndex(const char* text)
@@ -2066,20 +2098,20 @@
 
 int MC_MaxFormulaSize(void)
 {
-  return max_formula_size;
+  return MC_FORMULA_LEN;
 }
 
 int MC_MaxAnswerSize(void)
 {
-  return max_answer_size;
+  return MC_ANSWER_LEN;
 }
 
 void MC_ResetFlashCard(MC_FlashCard* fc)
 {
   if (!fc || !fc->formula_string || !fc->answer_string)
     return;
-  strncpy(fc->formula_string, " ", max_formula_size);
-  strncpy(fc->answer_string, " ", max_answer_size);
+  strncpy(fc->formula_string, " ", MC_FORMULA_LEN);
+  strncpy(fc->answer_string, " ", MC_ANSWER_LEN);
   fc->answer = 0;
   fc->difficulty = 0;
 }
@@ -2189,8 +2221,8 @@
         return NULL;
       }
 
-      snprintf(tnode->card.formula_string, max_formula_size, "%d", i);
-      snprintf(tnode->card.answer_string, max_formula_size, "%d", i);
+      snprintf(tnode->card.formula_string, MC_FORMULA_LEN, "%d", i);
+      snprintf(tnode->card.answer_string, MC_ANSWER_LEN, "%d", i);
       tnode->card.difficulty = 1;
       list = insert_node(list, *end_of_list, tnode);
       *end_of_list = tnode;
@@ -2296,8 +2328,8 @@
               return NULL;
             }
 
-            snprintf(tnode->card.answer_string, max_formula_size, "%d", ans);
-            snprintf(tnode->card.formula_string, max_formula_size,
+            snprintf(tnode->card.answer_string, MC_ANSWER_LEN, "%d", ans);
+            snprintf(tnode->card.formula_string, MC_FORMULA_LEN,
                      "%d %c %d = ?", i, operchars[k], j);
             tnode->card.difficulty = k + 1;
             list = insert_node(list, *end_of_list, tnode);
@@ -2331,8 +2363,8 @@
               return NULL;
             }
 
-            snprintf(tnode->card.answer_string, max_formula_size, "%d", i);
-            snprintf(tnode->card.formula_string, max_formula_size,
+            snprintf(tnode->card.answer_string, MC_ANSWER_LEN, "%d", i);
+            snprintf(tnode->card.formula_string, MC_FORMULA_LEN,
                      "? %c %d = %d", operchars[k], j, ans);
             tnode->card.difficulty = k + 3;
             list = insert_node(list, *end_of_list, tnode);
@@ -2365,8 +2397,8 @@
               return NULL;
             }
 
-            snprintf(tnode->card.answer_string, max_formula_size, "%d", j);
-            snprintf(tnode->card.formula_string, max_formula_size,
+            snprintf(tnode->card.answer_string, MC_ANSWER_LEN, "%d", j);
+            snprintf(tnode->card.formula_string, MC_FORMULA_LEN,
                      "%d %c ? = %d", i, operchars[k], ans);
             tnode->card.difficulty = k + 3;
             list = insert_node(list, *end_of_list, tnode);
@@ -2398,8 +2430,8 @@
           return NULL;
         }
 
-        snprintf(tnode->card.formula_string, max_formula_size, "%d ? %d", i,j);
-        snprintf(tnode->card.answer_string, max_formula_size,
+        snprintf(tnode->card.formula_string, MC_FORMULA_LEN, "%d ? %d", i,j);
+        snprintf(tnode->card.answer_string, MC_ANSWER_LEN,
                  i < j ? "<" : 
                  i > j ? ">" : 
                          "=");
@@ -2427,8 +2459,8 @@
   int i, j;
   char* beg = 0;
   char* end = 0;
-  char nans[max_answer_size];
-  char nformula[max_formula_size + max_answer_size]; //gets a bit larger than usual in the meantime
+  char nans[MC_ANSWER_LEN];
+  char nformula[MC_FORMULA_LEN + MC_ANSWER_LEN]; //gets a bit larger than usual in the meantime
   
   {
     //snprintf(nans, max_answer_size, "%s", card->answer_string);
@@ -2436,8 +2468,8 @@
     //insert old answer where question mark was
     for (i = 0, j = 0; card->formula_string[j] != '?'; ++i, ++j)
       nformula[i] = card->formula_string[j];
-    i += snprintf(nformula + i, max_answer_size - 1, "%s", card->answer_string);
-    snprintf(nformula + i, max_formula_size - i, "%s", card->formula_string + j + 1);
+    i += snprintf(nformula + i, MC_ANSWER_LEN - 1, "%s", card->answer_string);
+    snprintf(nformula + i, MC_FORMULA_LEN - i, "%s", card->formula_string + j + 1);
 
     //replace the new answer with a question mark
     if (f == MC_FORMAT_ANS_LAST)
@@ -2452,8 +2484,8 @@
     //we now have beg = first digit of number to replace, end = the char after
     sscanf(beg, "%s", nans);
     *beg = 0; //sequester the first half of the string
-    snprintf(card->formula_string, max_formula_size, "%s?%s", nformula, end);
-    snprintf(card->answer_string, max_answer_size, "%s", nans);
+    snprintf(card->formula_string, MC_FORMULA_LEN, "%s?%s", nformula, end);
+    snprintf(card->answer_string, MC_ANSWER_LEN, "%s", nans);
     card->answer = atoi(card->answer_string);
   }
 }

Modified: tuxmath/branches/lan/src/mathcards.h
===================================================================
--- tuxmath/branches/lan/src/mathcards.h	2009-07-08 21:49:52 UTC (rev 1162)
+++ tuxmath/branches/lan/src/mathcards.h	2009-07-08 22:56:51 UTC (rev 1163)
@@ -15,14 +15,14 @@
 #ifndef MATHCARDS_H
 #define MATHCARDS_H
 
-#define MC_DEBUG
+#include "transtruct.h"
+//#define MC_DEBUG
 #ifdef MC_DEBUG
 #define mcdprintf(...) printf(__VA_ARGS__)
 #else
 #define mcdprintf(...) 0
 #endif
 
-#define MC_USE_NEWARC
 
 /* different classes of problems TuxMath will ask */
 typedef enum _MC_ProblemType {
@@ -151,27 +151,8 @@
   int iopts[NOPTS];
 } MC_Options;
 
-#ifndef MC_USE_NEWARC
-/* struct for individual "flashcard" */
-typedef struct MC_FlashCard {
-  int num1;
-  int num2;
-  int num3;
-  int operation;
-  int format;
-  char formula_string[MC_FORMULA_LEN];
-  char answer_string[MC_ANSWER_LEN];
-} MC_FlashCard;
-#else
-/* experimental struct for a more generalized flashcard */
-typedef struct _MC_FlashCard {
-  char* formula_string;
-  char* answer_string;
-  int answer;
-  int difficulty;
-} MC_FlashCard;
-#endif
 
+
 /* struct for node in math "flashcard" list */
 typedef struct MC_MathQuestion {
   MC_FlashCard card;
@@ -225,6 +206,7 @@
 /*  tells MathCards that the question has been answered   */
 /*  correctly. Returns 1 if no errors.                    */
 int MC_AnsweredCorrectly(MC_FlashCard* q);
+int MC_AnsweredCorrectly_id(int id);
 
 /*  MC_NotAnsweredCorrectly() is how the user interface    */
 /*  tells MathCards that the question has not been        */

Modified: tuxmath/branches/lan/src/network.c
===================================================================
--- tuxmath/branches/lan/src/network.c	2009-07-08 21:49:52 UTC (rev 1162)
+++ tuxmath/branches/lan/src/network.c	2009-07-08 22:56:51 UTC (rev 1163)
@@ -1,535 +1,290 @@
+/*
+*  C Implementation: network.c
+*
+*       Description: Contains all the network realted functions , for LAN-based play in Tux,of Math Command.
+*
+*
+* Author: Akash Gangil, David Bruce, and the TuxMath team, (C) 2009
+* Developers list: <tuxmath-devel at lists.sourceforge.net>
+*
+* Copyright: See COPYING file that comes with this distribution.  (Briefly, GNU GPL).
+*/
 
-//** this file would contain all the network related functions**
-
-
-
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
 #include <unistd.h>
-#include "SDL.h"
+#include <fcntl.h> 
+
 #include "SDL_net.h"
-#include "network.h"
-#include "SDL.h"
+#include "transtruct.h"
+//#include "testclient.h"
 
 
-//*** ipaddress of the server and the port would be taken by the user @ the time he selects "LAN multiplayer" from the options menu..
+TCPsocket sd;           /* Server socket descriptor */
+SDLNet_SocketSet set;
 
-//***also should I fix the port beforehand or ask it from the user...
+//MC_FlashCard flash;    //current question
+/*int quit = 0;
 
+int Make_Flashcard(char *buf, MC_FlashCard* fc);
+int LAN_AnsweredCorrectly(MC_FlashCard* fc);
+int playgame(void);
+void server_pinged(void);*/
 
-extern char host[1024];
-extern char port[1024];
 
-int SendQuestion(MC_FlashCard* fc)                                                            //function to send a flashcard from the server to the client
+int setup_net(char *host, int port)
 {
-char *ch;
-IPaddress ip; //int *remoteip;
-TCPsocket server,client;
-//Uint32 ipaddr;
-Uint16 portnum;
+  IPaddress ip;           /* Server address */
+  int sockets_used;
+//  int len;
+//  char buf[NET_BUF_LEN];     // for network messages from server
+  char buffer[NET_BUF_LEN];  // for command-line input
+//  char *check1;
+  char name[NAME_SIZE]="Player 1";
 
+  if (SDLNet_Init() < 0)
+  {
+    fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
+    exit(EXIT_FAILURE);
+  }
+ 
+  /* Resolve the host we are connecting to */
+  if (SDLNet_ResolveHost(&ip, host, port) < 0)
+  {
+    fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
+    exit(EXIT_FAILURE);
+  }
+ 
+  /* Open a connection with the IP provided (listen on the host's port) */
+  if (!(sd = SDLNet_TCP_Open(&ip)))
+  {
+    fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
+    exit(EXIT_FAILURE);
+  }
 
-// initialize SDL
-if(SDL_Init(0)==-1)
-{
-printf("SDL_Init: %s\n",SDL_GetError());
-exit(1);
-}
+  /* We create a socket set so we can check for activity: */
+  set = SDLNet_AllocSocketSet(1);
+  if(!set) {
+    printf("SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
+    exit(EXIT_FAILURE);
+  }
 
-// initialize SDL_net
-if(SDLNet_Init()==-1)
-{
-printf("SDLNet_Init: %s\n",SDLNet_GetError());
-exit(2);
-}
+  sockets_used = SDLNet_TCP_AddSocket(set, sd);
+  if(sockets_used == -1) {
+    printf("SDLNet_AddSocket: %s\n", SDLNet_GetError());
+    // perhaps you need to restart the set and make it bigger...
+  }
 
+ snprintf(buffer, NET_BUF_LEN, 
+                       "%s\n",
+                       name);
+ 
+  if (SDLNet_TCP_Send(sd, (void *)buffer, NET_BUF_LEN) < NET_BUF_LEN)
+  {
+   fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
+   exit(EXIT_FAILURE);
+  }
+ 
+  return 1;
 
-portnum=(Uint16)strtol(port,NULL,0);
-
-// Resolve the argument into an IPaddress type
-if(SDLNet_ResolveHost(&ip,NULL,portnum)==-1)
-{
-printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
-exit(3);
 }
 
-// open the server socket																		
-server=SDLNet_TCP_Open(&ip);
-if(!server)
+int player_msg_recvd(char* buf,char* p)
 {
-printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
-return 1;
-}
-
-while(1)
-{
-
-// try to accept a connection
- client=SDLNet_TCP_Accept(server);
- if(!client)
-  {    // no connection accepted
-      //printf("SDLNet_TCP_Accept: %s\n",SDLNet_GetError());
-    SDL_Delay(100); //sleep 1/10th of a second
-    continue;
+  p = strchr(buf, '\t');
+  if(p)
+  { 
+    p++;
+    printf("%s\n", p);
+    return 1;
   }
-  
-
-              // read the buffer from client
-		SDLNet_TCP_Send(client,fc->formula_string,4);
-		SDLNet_TCP_Recv(client,ch,1);                                     //will send in the next item only when the first one is received
-                if(*ch=='1')
-                 {
-                  SDLNet_TCP_Send(client,fc->answer_string,4);
-		  SDLNet_TCP_Recv(client,ch,1);
-                  if(*ch=='1')
-                   { 
-                    SDLNet_TCP_Send(client,&(fc->answer),4);
-		    SDLNet_TCP_Recv(client,ch,1);
-                    if(*ch=='1')
-                    {
-                     SDLNet_TCP_Send(client,&(fc->difficulty),4);
-                     SDLNet_TCP_Recv(client,ch,1);
-                     if(*ch=='1')
-                      {		
-			break;
-                      }
-                    }
-                  }
-                 }
-                 
-       
-
+  else
+    return 0;
 }
 
-//	SDLNet_TCP_Close(client);	
-//	SDLNet_TCP_Close(server);
-        // shutdown SDL_net
-//	SDLNet_Quit();
 
-
-return 0;
-}
-
-
-int ReceiveQuestion(MC_FlashCard* fc)                                             //function for the client to receive the flashcard "from" the server
+int say_to_server(char statement[20])
 {
+  int len;
+  char buffer[NET_BUF_LEN];
 
-IPaddress ip;
-TCPsocket sock;
-Uint16 portnum;
-
-portnum=(Uint16) strtol(port,NULL,0);
-
-// initialize SDL
-if(SDL_Init(0)==-1)
-{
-printf("SDL_Init: %s\n",SDL_GetError());
-exit(1);
+   snprintf(buffer, NET_BUF_LEN, 
+                  "%s\n",
+                  statement);
+   len = strlen(buffer) + 1;
+   if (SDLNet_TCP_Send(sd, (void *)buffer, NET_BUF_LEN) < NET_BUF_LEN)
+   {
+     fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
+     exit(EXIT_FAILURE);
+   }
+  
+   return 1;
 }
 
-// initialize SDL_net
-if(SDLNet_Init()==-1)
-{
-printf("SDLNet_Init: %s\n",SDLNet_GetError());
-exit(2);
+int check_messages(char buf[NET_BUF_LEN])
+{ 
+  int x = 0,numready;
+  
+  //This is supposed to check to see if there is activity:
+  numready = SDLNet_CheckSockets(set, 0);
+  if(numready == -1)
+  {
+    printf("SDLNet_CheckSockets: %s\n", SDLNet_GetError());
+    //most of the time this is a system error, where perror might help you.
+    perror("SDLNet_CheckSockets");
+  }
+  else if(numready > 0)
+  {
+#ifdef LAN_DEBUG
+//  printf("There are %d sockets with activity!\n", numready);
+#endif
+   // check all sockets with SDLNet_SocketReady and handle the active ones.
+    if(SDLNet_SocketReady(sd))
+    {
+      buf[0] = '\0';
+      x = SDLNet_TCP_Recv(sd, buf, NET_BUF_LEN);
+      if( x <= 0)
+      {
+        fprintf(stderr, "In play_game(), SDLNet_TCP_Recv() failed!\n");
+        exit(EXIT_FAILURE);
+      }
+    }
+  }
+  return 1;
 }
 
-
-// Resolve the argument into an IPaddress type
-if(SDLNet_ResolveHost(&ip,host,portnum)==-1)
+int Make_Flashcard(char* buf, MC_FlashCard* fc)
 {
-printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
-exit(3);
-}
-
-//connect to the "host" @ port "portnum"
-sock=SDLNet_TCP_Open(&ip);
-
-while(!sock)
-{
- if(!sock)
- {
-  printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
-  sock=SDLNet_TCP_Open(&ip);
-
-  continue;
- }
-}	
-
-        SDLNet_TCP_Recv(sock,fc->formula_string,4);
-	SDLNet_TCP_Send(sock,"1",1); 		                  // send a conformation that the 1st item has been received				
-	SDLNet_TCP_Recv(sock,fc->answer_string,4);
-        SDLNet_TCP_Send(sock,"1",1);
-        SDLNet_TCP_Recv(sock,&(fc->answer),4);
-        SDLNet_TCP_Send(sock,"1",1);
-        SDLNet_TCP_Recv(sock,&(fc->difficulty),4);
+  int i = 0,tab = 0, s = 0;
+  char formula[MC_FORMULA_LEN];
+  sscanf (buf,"%*s%d%d%d%s",
+              &fc->question_id,
+              &fc->difficulty,
+              &fc->answer,
+              fc->answer_string); /* can't formula_string in sscanf in here cause it includes spaces*/
  
+  /*doing all this cause sscanf will break on encountering space in formula_string*/
+  /* NOTE changed to index notation so we keep within NET_BUF_LEN */
+  while(buf[i]!='\n' && i < NET_BUF_LEN)
+  {
+    if(buf[i]=='\t')
+      tab++; 
+    i++;
+    if(tab == 5)
+      break;
+  }
 
+  while((buf[i] != '\n') 
+    && (s < MC_FORMULA_LEN - 1)) //Must leave room for terminating null
+  {
+    formula[s] = buf[i] ;
+    i++;
+    s++;
+  }
+  formula[s]='\0';
+  strcpy(fc->formula_string, formula); 
 
- //       SDLNet_TCP_Close(sock);
-	
-	// shutdown SDL_net
-//	SDLNet_Quit();
+#ifdef LAN_DEBUG
+  printf ("card is:\n");
+  printf("QUESTION_ID       :      %d\n",fc->question_id);
+  printf("FORMULA_STRING    :      %s\n",fc->formula_string);
+  printf("ANSWER STRING     :      %s\n",fc->answer_string);
+  printf("ANSWER            :      %d\n",fc->answer);
+  printf("DIFFICULTY        :      %d\n",fc->difficulty);  
+#endif
 
+return 1;
+} 
 
 
-	return(0);
-}
 
-
-
-int SendInt(int x)
+int LAN_AnsweredCorrectly(MC_FlashCard* fc)
 {
+  int len;
+  char buffer[NET_BUF_LEN];
 
-IPaddress ip; 
-TCPsocket server,client;
-Uint16 portnum;
-char *ch;
-ch=(char*)x;
-
-// initialize SDL
-if(SDL_Init(0)==-1)
-{
-printf("SDL_Init: %s\n",SDL_GetError());
-exit(1);
-}
-
-// initialize SDL_net
-if(SDLNet_Init()==-1)
-{
-printf("SDLNet_Init: %s\n",SDLNet_GetError());
-exit(2);
-}
-
-
-portnum=(Uint16)strtol(port,NULL,0);
-
-// Resolve the argument into an IPaddress type
-if(SDLNet_ResolveHost(&ip,NULL,portnum)==-1)
-{
-printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
-exit(3);
-}
-
-// open the server socket																		
-server=SDLNet_TCP_Open(&ip);
-if(!server)
-{
-printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
-return 1;
-}
-
-while(1)
-{
-
-// try to accept a connection
- client=SDLNet_TCP_Accept(server);
- if(!client)
-  {    // no connection accepted
-      //printf("SDLNet_TCP_Accept: %s\n",SDLNet_GetError());
-    SDL_Delay(100); //sleep 1/10th of a second
-    continue;
+  snprintf(buffer, NET_BUF_LEN, 
+                  "%s %d\n",
+                  "CORRECT_ANSWER",
+                  fc->question_id);
+  len = strlen(buffer) + 1;
+  if (SDLNet_TCP_Send(sd, (void *)buffer, NET_BUF_LEN) < NET_BUF_LEN)
+  {
+    fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
+    exit(EXIT_FAILURE);
   }
-  
-
-              // read the buffer from client
-		SDLNet_TCP_Send(client,ch,1);
-		 
-       
-
+  return 1;
 }
+    
 
-//	SDLNet_TCP_Close(client);	
-//	SDLNet_TCP_Close(server);
-        // shutdown SDL_net
-//	SDLNet_Quit();
-
-
-return 0;
-}
-
-int ReceiveInt(int x)
+void cleanup_client(void)
 {
-
-IPaddress ip;
-TCPsocket server,client;
-Uint16 portnum;
-char *ch;
-
-// initialize SDL
-if(SDL_Init(0)==-1)
-{
-printf("SDL_Init: %s\n",SDL_GetError());
-exit(1);
-}
-
-// initialize SDL_net
-if(SDLNet_Init()==-1)
-{
-printf("SDLNet_Init: %s\n",SDLNet_GetError());
-exit(2);
-}
-
-
-portnum=(Uint16)strtol(port,NULL,0);
-
-// Resolve the argument into an IPaddress type
-if(SDLNet_ResolveHost(&ip,NULL,portnum)==-1)
-{
-printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
-exit(3);
-}
-
-// open the server socket																		
-server=SDLNet_TCP_Open(&ip);
-if(!server)
-{
-printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
-return 1;
-}
-
-while(1)
-{
-
-// try to accept a connection
- client=SDLNet_TCP_Accept(server);
- if(!client)
-  {    // no connection accepted
-      //printf("SDLNet_TCP_Accept: %s\n",SDLNet_GetError());
-    SDL_Delay(100); //sleep 1/10th of a second
-    continue;
-  }
   
+  if (set != NULL)
+  {
+    SDLNet_FreeSocketSet(set);    //releasing the memory of the client socket set
+    set = NULL;                   //this helps us remember that this set is not allocated
+  } 
 
-              // read the buffer from client
-		SDLNet_TCP_Recv(client,ch,1);
-		x=(int)(*ch);                                                              //typecasting so as to convert the char to int
-       
-
-}
-
-//	SDLNet_TCP_Close(client);	
-//	SDLNet_TCP_Close(server);
-        // shutdown SDL_net
-//	SDLNet_Quit();
-
-
-return 0;
-}
-
-
-int SendQuestionList(MC_MathQuestion* ql,int list_length)               //   function to send in the MC_MathQuestion data structure
-{                                                                       //   this helps in sending the question list from the server to the client
- int randomizer_value;
- randomizer_value=ql->randomizer;
- SendInt(randomizer_value);
- SendInt(list_length);
- while(ql!=NULL)
- {
-  SendQuestion(&(ql->card));
-  ql=ql->next;
- }
- return 0;
-}
-
-
-int ReceiveQuestionList(MC_MathQuestion* ql,int list_length)               //   function to receive in the MC_MathQuestion data structure
-{                                                                          //   this helps in receiving the question list 
- int m;
- ReceiveInt(ql->randomizer);
- ReceiveInt(list_length);
- for(m=list_length;m>0;m--)
- {
-  ReceiveQuestion(&(ql->card));
-  ql->next=NULL;
-  ql=ql->next;
- }
- return 0;
-}
-   
- 
-
-
-int lan_client_connect(char *host,char *port)            //here "host" is either the hostname or the ipaddress(of the server) in string
-{
-char message[]="Client got connected";
-int len;
-IPaddress ip;
-TCPsocket sock;
-Uint16 portnum;
-SDL_Event event;
-
-portnum=(Uint16) strtol(port,NULL,0);
-
-// initialize SDL
-if(SDL_Init(0)==-1)
-{
-printf("SDL_Init: %s\n",SDL_GetError());
-exit(1);
-}
-
-// initialize SDL_net
-if(SDLNet_Init()==-1)
-{
-printf("SDLNet_Init: %s\n",SDLNet_GetError());
-exit(2);
-}
-
-
-// Resolve the argument into an IPaddress type
-if(SDLNet_ResolveHost(&ip,host,portnum)==-1)
-{
-printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
-exit(3);
-}
-
-//connect to the "host" @ port "portnum"
-sock=SDLNet_TCP_Open(&ip);
-while(!sock)
-{
-
- while(SDL_PollEvent(&event)) 
+  if(sd != NULL)
   {
-    if(event.type==SDL_KEYDOWN)
-     {
-       if(event.key.keysym.sym==SDLK_ESCAPE)
-       return 7;
-     }
+    SDLNet_TCP_Close(sd);
+    sd = NULL;
   }
- if(!sock)
- {
- printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
- sock=SDLNet_TCP_Open(&ip);
-
- continue;
- }
 }
-	len=strlen(message);
 
-	// strip the newline
-	message[len]='\0';
-	
-	if(len)
-	{
-		int result;
-		
-		// print out the message
-		printf("Sending: %.*s\n",len,message);
 
-		result=SDLNet_TCP_Send(sock,message,len); // add 1 for the NULL
-		if(result<len)
-			printf("SDLNet_TCP_Send: %s\n",SDLNet_GetError());
-	}
 
-
-	SDLNet_TCP_Close(sock);
-	
-	// shutdown SDL_net
-	SDLNet_Quit();
-
-
-
-	return(0);
-}
-
-
-
-/***      server connection function    ****/
-
-
-int lan_server_connect(char *port)
+int evaluate(char statement[20])
 {
-IPaddress ip; //int *remoteip;
-TCPsocket server,client;
-//Uint32 ipaddr;
-Uint16 portnum;
-int len;
-SDL_Event event;
+  int ans;
+  char command[NET_BUF_LEN];
+  int len;
+  char buffer[NET_BUF_LEN];
+  char buf[NET_BUF_LEN];
 
-char message[1024];
-char waiting[]="WAITING FOR OTHER PLAYER(minimum 2 players required)";
+   snprintf(buffer, NET_BUF_LEN, 
+                  "%s\n",
+                  statement);
+   len = strlen(buffer) + 1;
+   if (SDLNet_TCP_Send(sd, (void *)buffer, NET_BUF_LEN) < NET_BUF_LEN)
+   {
+     fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
+     exit(EXIT_FAILURE);
+   }
+  
+  check_messages(buf);
+  player_msg_recvd(buf,command);
+  ans=atoi(command);
 
-// initialize SDL
-if(SDL_Init(0)==-1)
-{
-printf("SDL_Init: %s\n",SDL_GetError());
-exit(1);
+  return ans;
 }
 
-// initialize SDL_net
-if(SDLNet_Init()==-1)
-{
-printf("SDLNet_Init: %s\n",SDLNet_GetError());
-exit(2);
-}
 
 
-portnum=(Uint16)strtol(port,NULL,0);
+/*The Ping system is not yet used */
+void server_pinged(void)
+{ 
+  int len;
+  char buffer[NET_BUF_LEN];
 
-// Resolve the argument into an IPaddress type
-if(SDLNet_ResolveHost(&ip,NULL,portnum)==-1)
-{
-printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
-exit(3);
-}
-
-// open the server socket
-server=SDLNet_TCP_Open(&ip);
-if(!server)
-{
-printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
-return 1;
-}
-
-
-printf("%s\n",waiting);
-while(1)
-{
-  while( SDL_PollEvent( &event ) ) 
+  snprintf(buffer, NET_BUF_LEN, 
+                  "%s \n",
+                  "PING_BACK");
+  len = strlen(buffer) + 1;
+  if (SDLNet_TCP_Send(sd, (void *)buffer, NET_BUF_LEN) < NET_BUF_LEN)
   {
-    if(event.type==SDL_KEYDOWN)
-     {
-       if(event.key.keysym.sym==SDLK_ESCAPE)
-       return 7;
-     }
+    fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
+    exit(EXIT_FAILURE);
   }
-// try to accept a connection
- client=SDLNet_TCP_Accept(server);
- if(!client)
-  {    // no connection accepted
-      //printf("SDLNet_TCP_Accept: %s\n",SDLNet_GetError());
-    SDL_Delay(100); //sleep 1/10th of a second
-    continue;
-  }
-  
-
-              // read the buffer from client
-		len=SDLNet_TCP_Recv(client,message,1024);
-		if(!len)
-		{
-			printf("SDLNet_TCP_Recv: %s\n",SDLNet_GetError());
-			continue;
-		}
-
-		// print out the message
-		printf("Received: %.*s\n",len,message);
-                break;
-
-		if(message[0]=='Q')
-		{
-			printf("Quitting on a Q received\n");
-			break;
-		}
-                break;
+ 
+#ifdef LAN_DEBUG
+//   printf("Buffer sent is %s\n",buffer);
+#endif
+ 
 }
 
-	SDLNet_TCP_Close(client);	
-	SDLNet_TCP_Close(server);
-        // shutdown SDL_net
-	SDLNet_Quit();
 
 
-return 0;
-}
-
-

Modified: tuxmath/branches/lan/src/network.h
===================================================================
--- tuxmath/branches/lan/src/network.h	2009-07-08 21:49:52 UTC (rev 1162)
+++ tuxmath/branches/lan/src/network.h	2009-07-08 22:56:51 UTC (rev 1163)
@@ -1,22 +1,29 @@
-#ifndef NETWORK_H
-#define NETWORK_H
-
 /*
 
-network.h     - Provides routines for various networking functions to be used
-                in the LAN multiplayer game.
+        network.h
 
+        Description: Provides routines for various networking functions to be used
+                     in the LAN multiplayer game.
+        Author: David Bruce ,Akash Gangil and the TuxMath team, (C) 2009
 
+        Copyright: See COPYING file that comes with this distribution (briefly, GNU GPL version 2 or later)
+
 */
 
-#include "mathcards.h"
 
-int lan_server_connect(char *port);
-int lan_client_connect(char *host,char *port);
-int SendQuestion(MC_FlashCard* fc);
-int ReceiveQuestion(MC_FlashCard* fc);
-int ReceiveInt(int x);
-int SendInt(int x); 
-int SendQuestionList(MC_MathQuestion* ql,int list_length);
-int ReceiveQuestionList(MC_MathQuestion* ql,int list_length);
+#include "transtruct.h"
+
+
+#ifndef NETWORK_H
+#define NETWORK_H
+
+int setup_net(char *host, int port);
+int say_to_server(char *statement);
+int evaluate(char *statement);
+int LAN_AnsweredCorrectly(MC_FlashCard* fc);
+void cleanup_client(void);
+int check_messages(char *);
+int player_msg_recvd(char* buf,char* p);
+int Make_Flashcard(char* buf, MC_FlashCard* fc);
+void server_pinged(void);        //The ping system is not yet used and so is this function.
 #endif // NETWORK_H

Modified: tuxmath/branches/lan/src/setup.c
===================================================================
--- tuxmath/branches/lan/src/setup.c	2009-07-08 21:49:52 UTC (rev 1162)
+++ tuxmath/branches/lan/src/setup.c	2009-07-08 22:56:51 UTC (rev 1163)
@@ -37,7 +37,7 @@
 #endif
 
 #include "SDL_image.h"
-
+#include "transtruct.h"
 #include "options.h"
 #include "tuxmath.h"
 #include "mathcards.h"

Modified: tuxmath/branches/lan/src/titlescreen.c
===================================================================
--- tuxmath/branches/lan/src/titlescreen.c	2009-07-08 21:49:52 UTC (rev 1162)
+++ tuxmath/branches/lan/src/titlescreen.c	2009-07-08 22:56:51 UTC (rev 1163)
@@ -33,6 +33,7 @@
 #include "campaign.h"
 #include "factoroids.h"
 #include "multiplayer.h"
+#include "transtruct.h"
 #include "mathcards.h"
 #include "setup.h"     //for cleanup()
 #include "network.h"
@@ -2827,14 +2828,14 @@
     while (SDL_PollEvent(&event)) 
     {
       if(host==NULL)
-      {l=lan_server_connect(port);
+      {//l=lan_server_connect(port);
        if(l==7)
        return 7;
        printf("###############%d##############\n",l);
        return 0;  
       }
       else
-      {l=lan_client_connect(host,port);
+      {//l=lan_client_connect(host,port);
        if(l==7)
        return 7;
        printf("##############%d#################\n",l);




More information about the Tux4kids-commits mailing list