/* * rover.c * * This is the rover program from assignment 4. */ #include #include #define OM_DIAMETER 550 #define OM_RADIUS (OM_DIAMETER/2) #define LANDING_X 0 #define TARGET_X (100+100+OM_DIAMETER) #define OM_CENTER_X (100+OM_DIAMETER) int main (int argc, char *argv[]) { FILE *f, *g; float fuel, /* amount of fuel left */ distance, /* distance travelled */ xpos, /* x coordinate */ ypos, /* y coordinate */ h, /* length of hypotenuse; amount to go forward */ angle, /* current heading */ dx, /* difference in x coordinate */ dy, /* difference in y coordinate */ a, /* adjacent side length */ o, /* opposite side length */ dist; /* distance from target */ char command; /* current command */ int nread; /* number of things read by fscanf */ if (argc != 2) { fprintf (stderr, "not enough arguments\n"); exit (1); } f = fopen (argv[1], "r"); if (!f) { fprintf (stderr, "can't open file.\n"); exit (1); } /* initially at (0,0) */ xpos = LANDING_X; ypos = 0.0; /* heading east */ angle = PI/2; /* 15 L of fuel */ fuel = 15.0; /* get an initial command and parameter */ nread = fscanf (f, "%c %f\n", &command, &h); /* while fscanf works... */ while (nread == 2) { printf ("command: "); switch (command) { /* rotate; just change the heading */ case 'r': printf ("rotate %6.2f\n", h); angle += h * (PI/180.0); break; /* go forward */ case 'f': printf ("forward %6.2f\n", h); /* the system forms a right triangle * where 'p' is the hypotenuse, * 'a' is the adjacent side, and * 'o' is the opposite side. */ a = h * cos (angle); o = h * sin (angle); xpos += o; ypos += a; fuel -= h / 70.0; break; default: printf ("not recognized!\n"); } printf ("position: (%6.2f, %6.2f)\t", xpos, ypos); printf ("orientation: %6.2f\t", (float) (angle * (180.0/PI))); printf ("fuel: %6.2f\n", fuel); /* figure out how far we are from center of volcano */ dx = xpos - OM_CENTER_X; dy = ypos - 0.0; dist = sqrt (dx*dx + dy*dy); /* give warning if too close to the volcano */ if (dist < OM_RADIUS) fprintf (stderr, "we are on the volcano!\n"); nread = fscanf (f, "%c %f\n", &command, &h); } fclose (f); /* how close are we to the target */ dx = xpos - TARGET_X; dy = ypos - 0.0; dist = sqrt (dx*dx + dy*dy); if (fuel < 0.0) { fprintf (stderr, "out of fuel!\n"); } if (dist < 5.0) { fprintf (stderr, "within 5 kilometers; ok to take sample.\n"); } else { fprintf (stderr, "not within 5 kilometers; failed.\n"); } }