write a program that draws a graphical display of a 2D random walk using a Drawi
ID: 3566873 • Letter: W
Question
write a program that draws a graphical display of a 2D random walk using a DrawingPanel. Start a pixel walker in the middle of the panel. On each step, choose to move 1 pixel up, down, left, or right, then redraw the pixel (You can draw a single pixel by drawing a rectagle of size 1x1). MUST HAVE THE FOLLOWING IN THE PROGRAM CODE:
walk(Drawingpanel panel, Random rand);
MORE INSTRUCTIONS:
When the program runs, a 200x200 DrawingPanel appears with a white background. Then your program should perform a random walk within a circle of radius 100, drawn as a black-outlined centered circle. (In other words, the top-left corner of the circle's bounding box is at (0, 0), and its width and height are twice as large as the radius.) The walker is a single black pixel that begins in the center of the circle. At each step, the walker randomly moves its position up, down, left, or right by 1 pixel. The walker should choose between these four choices randomly with equal probability. The walk ends when the walker reaches the perimeter of the circle (when it walks so far that its distance from the center is greater than or equal to the circle's radius). You should assume that no run will require ? 999,999,999 moves.
Explanation / Answer
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
public class RandomWalk {
public static void main(String[] args) throws Exception {
Random rand=new Random();
DrawingPanel panel = new DrawingPanel (200, 200);
walk(panel,rand);
}
public static void walk(DrawingPanel panel, Random rand)
{
int steps = 999999999;
int xCenter=100,yCenter=100;
Graphics g = panel.getGraphics();
g.setColor(Color.BLACK);
g.drawOval(0, 0, 200, 200);
for (int i = 0; i < steps; i++) {
if(getDistance(100,100,xCenter,yCenter)>100)
{
break;
}
else
{
g.drawRect(xCenter, yCenter, 1, 1);
int move=getDirection(rand);
if(move==1)
{
// move top
yCenter-=1;
}
else if(move==2)
{
// move right
xCenter+=1;
}
else if(move==3)
{
// move down
yCenter+=1;
}
else
{
//move right
xCenter-=1;
}
panel.sleep(10);
}
}
}
public static int getDirection(Random rand)
{
return rand.nextInt(4)+1;
}
public static double getDistance(int x1,int y1,int x2,int y2 )
{
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.