#include "library.h" struct Actor { double xpos, ypos, speed, reach; int color, target; string victory; }; const int num_actors = 3; const int idx_boy = 0, idx_bull = 1, idx_tree = 2; const int field_w = 800, field_h = 600; Actor all[num_actors]; void init(); // a PROTOTYPE lets you move func def to the end void draw(); void update(double t); bool winner(); void main() { init(); make_window(field_w, field_h); set_pen_width(5); draw(); while (true) { wait(0.01); update(0.5); draw(); if (winner()) break; } } void update(double t) { for (int i = 0; i < num_actors; i += 1) { double currx = all[i].xpos, curry = all[i].ypos; int idx_target = all[i].target; double targx = all[idx_target].xpos, targy = all[idx_target].ypos; double dir = atan2(targx-currx, targy-curry); double dx = all[i].speed * t * sin(dir), dy = all[i].speed * t * cos(dir); all[i].xpos += dx; all[i].ypos += dy; } } double distance(double x1, double y1, double x2, double y2) { return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); } bool winner() { for (int i = 0; i < num_actors; i += 1) { double currx = all[i].xpos, curry = all[i].ypos; int idx_target = all[i].target; double targx = all[idx_target].xpos, targy = all[idx_target].ypos; double reach = all[i].reach; if (distance(currx, curry, targx, targy) < reach) { move_to(currx, curry); set_pen_color(all[i].color); write_string(all[i].victory); return true; } } return false; } void draw() { for (int i = 0; i < num_actors; i += 1) { set_pen_color(all[i].color); draw_point(all[i].xpos, all[i].ypos); } } void init() { all[idx_boy].xpos = 200; all[idx_boy].ypos = field_h - 5; all[idx_boy].speed = 1.3; all[idx_boy].color = color::blue; all[idx_boy].target = idx_tree; all[idx_boy].reach = 2; all[idx_boy].victory = "I'm Safe"; all[idx_bull].xpos = 400; all[idx_bull].ypos = 150; all[idx_bull].speed = 1.3; all[idx_bull].color = color::red; all[idx_bull].target = idx_boy; all[idx_bull].reach = 3; all[idx_bull].victory = "Graaaaah! Chomp!"; all[idx_tree].xpos = 700; all[idx_tree].ypos = 300; all[idx_tree].speed = 0; all[idx_tree].color = color::green; all[idx_tree].target = idx_tree; all[idx_tree].reach = 0; all[idx_tree].victory = "Tree Wins!"; }