189cadcf27c512a8a780f2f4b87e484bd3c9a0a1
[universe.git] / hit_shape.cc
1
2 // Written and (C) by Francois Fleuret
3 // Contact <francois.fleuret@idiap.ch> for comments & bug reports
4
5 #include "task.h"
6 #include "universe.h"
7 #include "manipulator.h"
8
9 class MoveSquare : public Task {
10
11   int _square_size;
12   int _nb_shapes;
13   Polygon **_shapes;
14   bool *_targets;
15   const static int world_width = 500;
16   const static int world_height = 500;
17
18 public:
19
20   virtual const char *name() { return "HIT_SQUARE"; }
21
22   virtual int nb_degrees() { return 1; }
23
24   virtual int width() { return world_width; }
25
26   virtual int height() { return world_height; }
27
28   void scramble(Universe *universe) {
29     scalar_t margin = sqrt(2)/2 * _square_size;
30     scalar_t x[] = { -_square_size/2, _square_size/2, _square_size/2, -_square_size/2 };
31     scalar_t y[] = { -_square_size/2, -_square_size/2, _square_size/2, _square_size/2 };
32
33     universe->clear();
34
35     for(int s = 0; s < _nb_shapes; s++) _shapes[s] = 0;
36
37     int s = 0;
38     for(int k = 0; k < _nb_shapes * 10 && s < _nb_shapes; k++) {
39       Polygon *p;
40 //       bool red = drand48() < 0.2;
41       bool red = 1-s%2;
42
43       if(red) p = new Polygon(0.5, 1.0, 0.0, 0.0, x, y, 4);
44       else    p = new Polygon(0.5, 1.0, 1.0, 0.0, x, y, 4);
45
46       p->set_position(margin + (world_width - 2 * margin) * drand48(),
47                       margin + (world_height - 2 * margin) * drand48(),
48                       2 * M_PI * drand48());
49       p->set_speed(0, 0, 0);
50       universe->initialize(p);
51       p->_nailed = true;
52       if(universe->collide(p)) delete p;
53       else {
54         universe->add_polygon(p);
55         _shapes[s] = p;
56         _targets[s] = red;
57         s++;
58       }
59     }
60   }
61
62   virtual void init(Universe *universe, int degree) {
63     _square_size = 150;
64     _nb_shapes = 2;
65     _shapes = new Polygon *[_nb_shapes];
66     _targets = new bool[_nb_shapes];
67     scramble(universe);
68   }
69
70   virtual void update(scalar_t dt, Universe *universe, Manipulator *manipulator) { }
71
72   virtual scalar_t reward(Universe *universe, Manipulator *manipulator) {
73     if(manipulator->grabbing()) {
74       for(int k = 0; k < _nb_shapes; k++) if(_shapes[k] == manipulator->grabbing()) {
75         bool hit = _targets[k];
76         if(hit && (drand48() < 0.25)) {
77           manipulator->force_release();
78           scramble(universe);
79           return  1.0;
80         }
81 //         manipulator->force_release();
82 //         scramble(universe);
83 //         if(hit) return  1.0;
84 //         else    return -1.0;
85       }
86     }
87     return 0.0;
88   }
89
90   virtual void draw(SimpleWindow *window) { }
91 };
92
93 extern "C" Task *new_task() {
94   return new MoveSquare();
95 }