import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class RandomWalker extends JFrame implements ActionListener
{
public static int width = 800, height = 480;
public static int startX, startY, stickX = width/2, stickY = height/2;
public static int totalSteps = 0, currentStep = 0;
public static double randomAngle = 0, distance = 0;
public JButton quitB, startB;
public JLabel enterStepsL;
public JTextField enterStepsTF, enterWidthTF;
public static RandomWalker frame;
public static Date lastTime;
public RandomWalker()
{
super("Random Walker by Garrett Gottlieb");
setSize(width, height);
setLayout(null); // using null layout, it is the most customizable
enterWidthTF = new JTextField("Enter width here (< 800)");
enterWidthTF.setBounds(0, 5, 200, 25);
enterStepsTF = new JTextField("Enter # steps here");
enterStepsTF.setBounds(200, 5, 200, 25);
startB = new JButton("Start");
startB.setBounds(400, 0, 100, 30);
quitB = new JButton("Quit");
quitB.setBounds(500, 0, 100, 30);
startB.addActionListener(this);
quitB.addActionListener(this);
add(enterWidthTF);
add(enterStepsTF);
add(startB);
add(quitB);
setVisible(true);
}
public void paint(Graphics g)
{
g.clearRect(0, 0, width + 100, height + 120); // clear screen
// draw ubercool stickman
g.drawOval(stickX, stickY, 40, 40); // head
g.drawLine(stickX + 20, stickY + 40, stickX + 20, stickY + 80); // body
g.drawLine(stickX + 20, stickY + 80, stickX, stickY + 120); // left leg
g.drawLine(stickX + 20, stickY + 80, stickX + 40, stickY + 120); // right leg
g.drawLine(stickX + 20, stickY + 65, stickX - 20, stickY + 50); // left arm
g.drawLine(stickX + 20, stickY + 65, stickX + 60, stickY + 50); // right arm
g.drawString(distance + " pixels away after " + currentStep + " steps.", stickX, stickY - 30);
}
public static void main(String[] args)
{
frame = new RandomWalker();
}
public static void doRandomWalk()
{
stickX = width/2;
stickY = height/2;
startX = stickX;
startY = stickY;
frame.repaint();
for(int i = 0; i < totalSteps; i++)
{
randomAngle = Math.random() * Math.PI * 2;
stickX += Math.sin(randomAngle) * 10;
stickY += Math.cos(randomAngle) * 10;
//System.out.println(stickX + ", " + stickY + " minus " + startX + ", " + startY);
distance = Math.round(
Math.sqrt(
Math.pow(stickX - startX, 2) + Math.pow(stickY - startY, 2)
)
);
if(stickX > width - 100)
{
stickX = 20;
}
else if(stickX < 20)
{
stickX = width - 100;
}
if(stickY > height - 120)
{
stickY = 80;
}
else if(stickY < 80)
{
stickY = height - 120;
}
currentStep = i + 1;
frame.repaint();// **************************
lastTime = new Date();
while((new Date()).getTime() - lastTime.getTime() < 50) {frame.repaint();} // **********
}
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == startB)
{
totalSteps = Integer.parseInt(enterStepsTF.getText());
width = Integer.parseInt(enterWidthTF.getText());
frame.setSize(width, height);
doRandomWalk();
}
else
System.exit(0);
}
} |