[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Putting it all together Up: Dodgems: A longer exercise Previous: Decision Routine

Creating the Dodgem class

We have all the subsidary routines. Here's a workable class definition
class dodgem {
private:
int x;
int y;
int radius;
int speed;
int max_speed;
string name; // name of driver
Team team;
void check_wall_collision();
int best_direction();
void draw();

public:

// Constructor
dodgem(Team t, string driver);
int current_direction;
int score;
int getx() { return x;}
int gety() { return y;}
int getradius() { return radius;}
Team getteam()  { return team;}
string getname() {return name;}
void print();
void move();
void undraw();
};

Most of the class functions provide public access to private values. draw() and undraw() call draw_circle and undraw_circle. print() displays diagnostic information. You can write these inline now. The other class functions might best be placed outside the main class definition - e.g. write dodgem::move() { ... } etc.

The constructor function fills in the team and name fields. Use switch(t) to set radius and max_speed fields - values in the range 5 to 15 should be ok. Set score to 0 and speed to max_speed. x, y and current_direction can be initialised using the random_integer integer routine. Don't worry for the moment about dodgems being created on top of others, but do create them so that they don't project over the arena's edge. Finish the constructor by calling draw().

check_wall_collision() uses the current coordinates to determine whether the dodgem has crashed against a wall. If there's a collision, set x or y so that the dodgem is just touching the wall, and set the current_direction perpendicular to the wall, towards the center. Write it now.

best_direction() calculates the way the dodgem would like to go if it could turn that far. For the moment just try to circle clockwise, but if the dodgem is partly outside the inscribed circle of the arena, try to head towards the centre.

move() calls best_direction() then which_way() to decide how to change the current_direction. The dodgem is then removed from the screen and new coordinates calculated. check_wall_collision() is called, then the dodgem redrawn.


next up previous contents
Next: Putting it all together Up: Dodgems: A longer exercise Previous: Decision Routine
Tim Love
2001-07-05