In: Computer Science
Please use Java language with comments! Thanks!
Write a program that will display multiple dots move across the Frame and randomly change direction when they hit the edge of the screen. Do this by creating a Dot class and making each dot an object of that class. You may reuse code written in class for this part of the assignment. Create a subclass of the Dot class called PlayerDot that is controlled by the player through keyboard input (arrow keys) instead of moving randomly. You only need one object of this class.
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
class dot extends JPanel implements Runnable
{ int x=0,y=0;
int flag=0;
Thread t;
boolean b;
dot()
{
start();
}
public void paint(Graphics g){
//g.drawLine(10, 10, 200, 300);
getRootPane().setBackground(Color.BLACK);
if(flag==0) {
g.setColor(Color.BLACK);
g.drawRect(x, y, 2, 2);
g.setColor(Color.red);
g.drawRect(x+1, y+1, 2, 2);
}
else {
g.setColor(Color.BLACK);
g.drawRect(x, y, 2, 2);
g.setColor(Color.red);
g.drawRect(x-1, y-1, 2, 2);
}
}
public void start() {
t = new Thread(this);
b = false;
t.start();
}
public void run () {
char ch;
for(;;) {
try {
repaint();
Thread.sleep(10);
if((x<400 || y<400)&& flag==0)
{
x++;
y++;
}
else if(x==400 || y==400)
{
flag=1;
}
if (flag==1)
{
x--;
y=y-1;
}
}
catch(InterruptedException e) {}
}
}
}
public class test extends JFrame{
test()
{int x,y;
JFrame frame= new JFrame("Moving
dot");
frame.add(new dot());
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
public static void main(String[] args){
test t1 = new
test();
}