TP 13 exo2: Implement the missing bits to do a full game.
[TD_C.git] / TP_13 / exo2 / src / main.c
index 0606beba47b507e5f49dbf755df029a907a27075..390bc40005122a294846808868852871354b1235 100644 (file)
@@ -8,8 +8,9 @@
 
 int main() {
     int row, col, errno = 0, round = 0, player = 0, key_pressed;
-    char* top_msg = "";
-    char* back_msg = "";
+    const int str_max_length = 255;
+    char* top_msg = malloc(str_max_length * sizeof(char));
+    char* back_msg = malloc(str_max_length * sizeof(char));
 
     initscr();
     getmaxyx(stdscr, row, col);
@@ -28,19 +29,21 @@ int main() {
     print_board(base_y, base_x);
 
     do {
-        if (round % 2 == 0 || round == 0) {
-            player = 0;
-            top_msg = "Joueur 1 joue";
-        } else {
+        if (errno == 0) round++;
+
+        if (round % 2 == 0) {
             player = 1;
             top_msg = "Joueur 2 joue";
+        } else {
+            player = 0;
+            top_msg = "Joueur 1 joue";
         }
 
         mvprintw(base_y - 2, (base_x + 7 - strlen(top_msg)/2), top_msg);
-        mvprintw(base_y + 10, (base_x + 7 - strlen(back_msg)/2), back_msg);
 
         print_coordinates(coordinates_array, base_y, base_x);
 
+        /* getch() is blocking */
         key_pressed = getch();
         switch (key_pressed) {
             case 'a':
@@ -71,25 +74,36 @@ int main() {
                 new_coordinates = set_coordinates(3, 3, player);
                 break;
             default:
-                continue;
+                /* set invalid coordinates */
+                new_coordinates = set_coordinates(0, 0, player);
                 break;
         }
 
-        errno = add_coordinates(new_coordinates, coordinates_array);
+        errno = add_coordinates(new_coordinates, coordinates_array, round);
 
         if (errno == 2) {
             back_msg = "Choisir une case vide";
-            continue;
         } else if (errno == 3) {
             back_msg = "Coordonnees invalides";
-            continue;
+        } else if (errno == 1) {
+            back_msg = "Tableau rempli sans gagnant: egalite";
+        } else if (errno == 4) {
+            back_msg = "Erreur inconnue";
         } else if (errno == 0) {
+            /* FIXME: properly zero the string */
             back_msg = "";
         }
 
-        round++;
+        mvprintw(base_y + 10, (base_x + 7 - strlen(back_msg)/2), back_msg);
+
+        refresh();
+
+    } while (errno != 1);
 
-    } while (errno == 0 || errno == 2);
+    if (!top_msg)
+        free(top_msg);
+    if (!back_msg)
+        free(back_msg);
 
     endwin();