#include "library.h" bool close(double a, double b) { return fabs(a-b) < 0.1; } bool close(double x1, double y1, double x2, double y2) { return close(x1, x2) && close(y1, y2); } double direction_from_a_to_b(double ax, double ay, double bx, double by) { return atan2(bx-ax, ay-by); } void main() { double field_w=500, field_h=400, edge=100; double tree_x=400, tree_y=200; double bull_x=500, bull_y=150; double boy_x=100, boy_y=500; double bull_spd=3, boy_spd=2, delta_t=0.003; bool is_boy_safe = false; double total_time = 0.0; make_window(field_w+2*edge, field_h+2*edge); set_pen_color(color::green); fill_rectangle(edge, edge, field_w, field_h); set_pen_color(color::brown); set_pen_width(10); draw_point(tree_x, tree_y); set_pen_width(2); // this creates a new variable called "output". // ofstream is a type just like int or double or bool. // it represents a stream of text being output to a file. ofstream output("data.txt"); // that caused a file on disc called "data.txt" to be created. // from now on, output << can be used just like cout <<, but // it will add things to the file instead of displaying them // in the text window. while (true) { total_time += delta_t; output << "time " << total_time << ": "; // the boy runs straight to the tree: // work out the direction he runs double ang = direction_from_a_to_b(boy_x, boy_y, tree_x, tree_y); // work out how far he runs in 0.1 seconds double dist = boy_spd * delta_t; // work out where he will be 0.1 seconds later double boy_new_x = boy_x + dist * sin(ang); double boy_new_y = boy_y - dist * cos(ang); // draw a line showing these few inches of progress set_pen_color(color::blue); move_to(boy_x, boy_y); draw_to(boy_new_x, boy_new_y); // has he reached the tree yet? if (close(boy_new_x, boy_new_y, tree_x, tree_y)) { write_string("Boy Safe!"); is_boy_safe = true; } // Now we have to do exactly the same calculations for the bull // running towards the bull. // Lots of repeated code, very bad programming style. We must // design a function to do it. ang = direction_from_a_to_b(bull_x, bull_y, boy_x, boy_y); dist = bull_spd * delta_t; double bull_new_x = bull_x + dist * sin(ang); double bull_new_y = bull_y - dist * cos(ang); set_pen_color(color::red); move_to(bull_x, bull_y); draw_to(bull_new_x, bull_new_y); if (close(bull_new_x, bull_new_y, boy_new_x, boy_new_y)) { if (! is_boy_safe) write_string("Boy Eaten!"); break; } boy_x = boy_new_x; boy_y = boy_new_y; bull_x = bull_new_x; bull_y = bull_new_y; output << "boy at (" << boy_x << ", " << boy_y << "), "; output << "bull at (" << bull_x << ", " << bull_y << ")\n"; } cout << "Finished\n"; }