FamousPhil.com -- Home My Calendar Youtube LinkedIn Facebook MySpace Twitter RSS Blog Feed

Blog Navigation

Partners

Latest Activity

Another way to stop the unwanted calls even when you’re on the Do Not Call list

Phil explains how to use the old telephone tones to wane off telemarketers!



A Monte Carlo Simulation using Java

I was bored today with John and we thought we’d make a ball move on the screen.  After 10 minutes we decided to do a Monte Carlo simulation with the ball to get a cool drawing.  Forty minutes later, here is what we came up with, it kind of looks like a dog or a cow’s head :)

Here is the code that produced this:

package us.matthouse.circle;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.Timer;

public class Circle extends JFrame implements ActionListener{
	Timer t;
	int x = 300;
	int y = 300;
	int z[][] = new int[600][600];

	public Circle(){
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(600, 600);
		this.setLocation(50, 50);
		setVisible(true);

		for(int i=0; i<600; i++){
			for(int j=0; j<600; j++){
				z[i][j] = 0;
			}
		}

		t = new Timer(10, this);
		t.start();
	}

	public void paint(Graphics g){
		g.setColor(Color.white);
		g.fillRect(0, 0, 600, 600);

		g.setColor(Color.black);
		for(int i=0; i<600; i++){
			for(int j=0; j<600; j++){
				if(z[i][j] == 1){
					g.fillRect(i, j, 1, 1);
				}
			}
		}

		g.setColor(Color.green);
		g.fillOval(x, y, 5, 5);
	}

	public static void main(String[] args){
		new Circle();
	}

	public void actionPerformed(ActionEvent e){

		Random r = new Random();
		int k = r.nextInt(3) - 1;
		x = x + k;
		k = r.nextInt(3) - 1;
		y = y + k;

		z[x][y] = 1;

		if (y < 50){
			y++;
		}else if(x < 50){
			x++;
		}else if(x > 550){
			x--;
		}else if(y > 550){
			y--;
		}
		repaint();

	}

}

Tags: , , , ,
Posted in Programming

This entry was posted on Thursday, January 27th, 2011 at 12:52 am and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply


*