Create Laser.java
// An example code to demonstrate how to use the GameSpace and Vector class.
// Need to import below for the Vector class
import java.util.*;
class Laser extends GameSpace {
// Constructor
public Laser(int w, int h, int num) {
super(w, h);
_num = num;
}
// The main function
public static void main(String[] args) {
// Check for the command line arguments
if (args.length != 1) {
System.err.println("Usage: java Laser num");
System.exit(-1);
}
// Instantiate a Laser object and then run it
newLaser(args[0]).run();
}
// Return a new Laser class
private static Laser newLaser(String num) {
return (new Laser(600, 400, Integer.parseInt(num)));
}
// The sleep function
private void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
}
}
// The main loop
public void run() {
while (true) {
// Randomly generate a number of lines
for (int i = 0; i < _num; i++) {
int x1 = (int)(Math.random() * 600);
int y1 = (int)(Math.random() * 400);
int x2 = (int)(Math.random() * 600);
int y2 = (int)(Math.random() * 400);
cLines.push_back(new Line(this, x1, y1, x2, y2));
}
// Draw the lines
cLines.draw();
// Clear the lines
cLines.clear();
// Update the canvas
nextTimeStep();
// Pause for 100ms
sleep(100);
}
}
// A private line class
class Line {
private Laser _cLaser = null;
private int _x1, _y1, _x2, _y2;
Line(Laser cLaser, int x1, int y1, int x2, int y2) {
_cLaser = cLaser;
_x1 = x1;
_y1 = y1;
_x2 = x2;
_y2 = y2;
}
// A class should know how to draw itself!!!
public void draw() {
_cLaser.drawLine(_x1, _y1, _x2, _y2, 1.0f, 0.0f, 0.0f);
}
}
// A private class to keep track of a collection of lines
class Lines extends Vector<Line> {
public void push_back(Line l) {
add(l);
}
public void draw() {
for (int i = 0; i < size(); i++) {
get(i).draw();
}
}
}
private int _num = 0; // Batch of lines
private Lines cLines = new Lines(); // A collection of lines
}