import java.applet.*; import java.awt.*; public class turtle extends Applet { Graphics g; <.vars.> <.turtle functions.> public void init() { <.initial state.> <.draw interface.> } public void paint(Graphics g) { this.g = g; <.execute commands.> } public boolean action(Event e,Object o) { <.get command.> repaint(); return true; } } -_-_-
The turtle can move forward without trace, move forward while tracing its path, and rotate.
void Move(int x, int y){ this.x += x; this.y -= y; } void Move(int r){ x += (int) (r * Math.cos(d)); y -= (int) (r * Math.sin(d)); } void Line(int x, int y){ g.drawLine( this.x, this.y, this.x+x, this.y-y ); Move(x,y); } void Line(int r){ Line( (new Double(r * Math.cos(d))).intValue(), (new Double( r * Math.sin(d) )).intValue() ); } void Rotate(int d){ this.d += d * 3.14 / 180; while( 6.28 < this.d ){ this.d -= 6.28; } while( this.d < 0 ){ this.d += 6.28; } } -_-_-
The text field may be modified by the users.
Button moveButton, lineButton, clearButton, rotateButton; TextField in; -_-_-
clearButton = new Button("Clear"); add(clearButton); moveButton = new Button("Move"); add(moveButton); lineButton = new Button("Line"); add(lineButton); rotateButton = new Button("Rotate"); add(rotateButton); in = new TextField(3); add(in); in.setText( "50" ); -_-_-
int i; x = 150; y = 150; d = 0; for( i=0; i<N; i+=2 ){ switch( command[i] ) { case <.Line op.>:{ Line( command[i+1] ); break; } case <.Move op.>:{ Move( command[i+1] ); break; } case <.Rotate op.>:{ Rotate( command[i+1] ); break; } } } -_-_-
if("Clear".equals(o)) { <.initial state.> } else{ if( "Line".equals(o)){ command[N]=<.Line op.>; } if( "Move".equals(o)){ command[N]=<.Move op.>; } if("Rotate".equals(o)){ command[N]=<.Rotate op.>; } String s = new String( in.getText() ); Integer i = new Integer( s ); command[N+1]= i.intValue(); N+=2; } -_-_-
int command[] = new int[300];
-_-_-
1
-_-_-
2
-_-_-
3
-_-_-
N = 0;
-_-_-
int N; int x, y; double d; -_-_-
"javac turtle.java"