Pike

Contributed by Chris Rathman

Pike Script (shape.pike)


int main(int argc, string *argv) {
   // set up some shape instances
   array (Shape) scribble = allocate(2);
   scribble[0] = Rectangle(10, 20, 5, 6);
   scribble[1] = Circle(15, 25, 8);

   // iterate through the array and handle shapes polymorphically
   for (int i = 0; i < 2; i++) {
      scribble[i]->draw();
      scribble[i]->rMoveTo(100, 100);
      scribble[i]->draw();
   }

   // access a rectangle specific function
   Rectangle arectangle = Rectangle(0, 0, 15, 15);
   arectangle->setWidth(30);
   arectangle->draw();

   return 0;
}

class Shape {
   int x;
   int y;

   // constructor for shape class
   void create(int newx, int newy) {
      moveTo(newx, newy);
   }

   // accessors for x & y
   int getX() { return x; }
   int getY() { return y; }
   void setX(int newx) { x = newx; }
   void setY(int newy) { y = newy; }

   // move the x & y position of the object
   void moveTo(int newx, int newy) {
      setX(newx);
      setY(newy);
   }
   void rMoveTo(int deltax, int deltay) {
      moveTo(getX() + deltax, getY() + deltay);
   }

   // pseudo virtual routine
   void draw() { }
}

class Rectangle {
   inherit Shape;
   int width;
   int height;

   // constructor for rectangle class
   void create(int newx, int newy, int newwidth, int newheight) {
      ::create(newx, newy);
      setWidth(newwidth);
      setHeight(newheight);
   }

   // accessors for width & height
   int getWidth() { return width; }
   int getHeight() { return height; }
   void setWidth(int newwidth) { width = newwidth; }
   void setHeight(int newheight) { height = newheight; }

   // draw the rectangle
   void draw() {
      write("Drawing a Rectangle at:(%d,%d), width %d, height %d\n",
         getX(), getY(), getWidth(), getHeight());
   }
}

class Circle {
   inherit Shape;
   int radius;

   // constructor for circle class
   void create(int newx, int newy, int newradius) {
      ::create(newx, newy);
      setRadius(newradius);
   }

   // accessors for the radius
   int getRadius() { return radius; }
   void setRadius(int newradius) { radius = newradius; }

   // draw the circle
   void draw() {
      write("Drawing a Circle at:(%d,%d), radius %d\n",
         getX(), getY(), getRadius());
   }
}

Output

Drawing a Rectangle at:(10,20), width 5, height 6
Drawing a Rectangle at:(110,120), width 5, height 6
Drawing a Circle at:(15,25), radius 8
Drawing a Circle at:(115,125), radius 8
Drawing a Rectangle at:(0,0), width 30, height 15

Chris Rathman / Chris.Rathman@tx.rr.com