James Cummins / Mbed 2 deprecated el17jnc

Dependencies:   mbed

Revision:
36:9f7463a65fe0
Parent:
32:eff573ad8e42
Child:
38:a85bc227b907
--- a/Classic_Engine/ClassicEngine.cpp	Sat May 04 18:56:38 2019 +0000
+++ b/Classic_Engine/ClassicEngine.cpp	Mon May 06 00:05:52 2019 +0000
@@ -34,10 +34,10 @@
 bool ClassicEngine::finished(){
     bool finished = false;
     if(_abs_ball_pos.x > 402   &&       //these are the range of coords the ball
-       _abs_ball_pos.x < 407   &&       //can have as it crosses the finish line
+       _abs_ball_pos.x < 403   &&       //can have as it crosses the finish line
        _abs_ball_pos.y > 101   &&       //must be given as a range rather than an
        _abs_ball_pos.y < 141   ){       //exact number as .x and .y are floats so 
-           finished = true;             //will never exactly equal 405
+           finished = true;             //will never exactly equal 402
     }
     else{ finished = false; }
     printf("ball pos = %f , %f   |   finished = %d\n", _abs_ball_pos.x, _abs_ball_pos.y, finished);
@@ -45,8 +45,9 @@
 }
 
 void ClassicEngine::mode_complete(N5110 &lcd, Gamepad &gamepad, int fps){
+    float time_taken;
     while(!(gamepad.check_event(gamepad.A_PRESSED))){
-        float time_taken = _frames / fps;
+        time_taken = _frames / fps;
         char buffer[6];
         sprintf(buffer, "%4.f", time_taken);
         lcd.clear();
@@ -58,6 +59,7 @@
         lcd.refresh();
         wait(0.2);
     }
+    write_high_scores(time_taken);
 }
 
 bool ClassicEngine::mode_failed(N5110 &lcd, Gamepad &gamepad, Ball &ball, Map &map){
@@ -77,4 +79,45 @@
             break; }
     }
     return back_to_start_menu;
-}
\ No newline at end of file
+}
+
+void ClassicEngine::read_high_scores(){
+    FILE *fp;
+    fp = fopen("/sd/classichighscores.txt", "r");
+    
+    if(fp == NULL){
+        printf("Error: Could not open file");
+    } else {
+        int i = 0;
+        rewind(fp);
+        
+        while(fscanf(fp, "%d,%f", &_index_array[i], &_array_of_values[i]) != EOF){
+            i++;
+        }
+        fclose(fp);
+    }
+}
+
+void ClassicEngine::check_high_score(int time_taken){
+    read_high_scores();
+    for(int i = 4; i >= 0; i--){
+        if(_array_of_values[i] > time_taken){
+            _array_of_values[i+1] = _array_of_values[i];
+            _array_of_values[i] = time_taken;
+        }
+    }
+}
+
+void ClassicEngine::write_high_scores(int time_taken){
+    check_high_score(time_taken);
+    FILE *fp;
+    fp = fopen("/sd/classichighscores.txt", "w");
+    if(fp == NULL){
+        printf("Error: Could not open file");
+    } else {
+        for(int i = 0; i < 5; i++){
+            fprintf(fp, "%d, %f\n", _index_array[i], _array_of_values[i]);
+        }
+        fclose(fp);
+    }
+}