| JRobo.java |
1 // JRobo Basic JRobo class with rect method added
2 // Author: David 4/9/99
3
4 import java.awt.*;
5
6 public class JRobo
7 {
8
9 int x; // current x, y location
10 int y;
11 boolean draw; // pen up/down
12 int heading; // direction - in degrees
13
14 Graphics robog; // keep info about where to draw
15
16 // Constructor
17 JRobo( Graphics g )
18 {
19 x = 200;
20 y = 150;
21 draw = true;
22 heading = 0;
23 robog = g;
24 }
25
26 // r - Turn Right
27 public void r( int degrees )
28 {
29 heading = ( heading + degrees ) % 360;
30 }
31
32 // l - Turn Left
33 public void l( int degrees )
34 {
35 heading = ( heading - degrees ) % 360;
36 }
37
38 // f - Move forward
39 public void f( int distance )
40 {
41 int dx, dy;
42 dx = ( int ) Math.round( distance * Math.sin( heading * 2 * 3.142 / 360 ) * 500/1000 );
43 dy = ( int ) Math.round( distance * -Math.cos( heading * 2 * 3.142 / 360 ) * 500/1000 );
44 if (draw)
45 robog.drawLine( x, y, x + dx, y + dy );
46 x = x + dx;
47 y = y + dy;
48 }
49
50 // p - Change pen state
51 public void p( )
52 {
53 draw = ! draw;
54 }
55
56 // rect - Draw rectangle with given height and width
57 // Pre: Facing north, pen down, bottom left corner.
58 // Post: as pre-cond., with rectangle drawn.
59 public void rect( int height, int width )
60 {
61 f( height );
62 r( 90 );
63 f( width );
64 r( 90 );
65 f( height );
66 r( 90 );
67 f( width );
68 r( 90 );
69 }
70
71 } // end JRobo class
72