/*********************************************************

File: BrownianMotion2.java
Author: Jim Carlson (copyright) 1996
web: http://www.math.utah.edu/~carlson
e-mail: carlson@math.utah.edu
Date:June 6, 1996


Legal stuff: All rights reserved, but noncommercial use is free

**********************************************************/

import java.applet.*;
import java.awt.*;
import java.util.Random;

public class BrownianMotion2 extends Applet implements Runnable {

	int thisHeight, thisWidth;
	
	Thread runner;
	boolean running;
	int delay;
	
	Image offscreenImg;
	Graphics offscreenG;
	
	
	int trial, nSteps;
	double x, y;
	double dx;
	double dy;
	int dot_r;
	
	public void init() {
	
		thisHeight = this.size().height; thisWidth = this.size().width;
		offscreenImg = createImage( this.size().width, this.size().height );
		offscreenG = offscreenImg.getGraphics();
		
		String s = getParameter("delay");
		if ( s != null )
			delay = Integer.parseInt( s );
		else
			delay = 100;
		
		s = getParameter("nSteps");	
		if ( s != null )
			nSteps = Integer.parseInt( s );
		else
			nSteps = 60;
			
		s = getParameter("dx");	
		if ( s != null )
			dx = Double.valueOf( s ).doubleValue();
		else
			dx = 10;
			
		s = getParameter("dy");	
		if ( s != null )
			dy = Double.valueOf( s ).doubleValue();
		else
			dy = 10;
			
		s = getParameter("dot_r");	
		if ( s != null )
			dot_r = Integer.parseInt( s );
		else
			dot_r = 2;

			
		x = 0; y = 0;
		trial = 0;
		
		offscreenG.setColor( Color.lightGray );
		offscreenG.fillRect( 0, 0, thisWidth, thisHeight );
		offscreenG.setColor( Color.black );
		offscreenG.fillArc( sx(x), sy(y), 10, 10, 0, 360 );
			
	}
	
	public void start() {
		
		if ( runner == null ) {
			runner = new Thread(this);
			running = true;
			runner.start();
		}
	}
	
	public void stop() {
	
		if ( runner != null ) {
			runner.stop();
			runner = null;
		}
		
	}
	
	
	public void run() {
	
		Random R = new Random();
	
		while( true ) {
		
			trial++;
			x = 0; y = 0;
			
			for( int i = 0; i < 60; i++ ) {
				x += ( R.nextDouble() - 0.5 )*dx; 
		    	y += ( R.nextDouble() - 0.5 )*dy;
			}
			
			offscreenG.setColor( Color.red );
			offscreenG.fillArc( sx(x), sy(y), dot_r, dot_r, 0, 360 );
			showStatus("trial = "+trial);	
			repaint();
			try { Thread.sleep( delay ); }
			catch ( InterruptedException e ) { }
		
		}
	}
	
	public void update( Graphics g ) {
		paint (g);
	}
	
	public void paint( Graphics g ) {
		
		g.drawImage( offscreenImg, 0, 0, this );
		
	}
	
	public boolean mouseDown( Event evt, int x, int y ) {
	
		if (running) {
			running = false;
			runner.suspend();
		}
		else {
			running = true;
			runner.resume();
		}
		return true;
		
	}
	
	int sx( double x ) {
	
		return (int) (x + thisWidth/2);
		
	}
	
	int sy( double y ) {
	
		
		return (int) (-y + thisHeight/2);
		
	}
	
	
}
	
