import java.awt.*; import javax.swing.*; import java.awt.event.*; public class MissileLauncher { private static final int X_SIZE = 600, Y_SIZE = 800; public static void main(String[ ] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(X_SIZE, Y_SIZE); GraphicsPanel panel = new GraphicsPanel(); panel.setFocusable(true); frame.add(panel); frame.setVisible(true); } private static class GraphicsPanel extends JPanel implements KeyListener, ActionListener { private int x,y; // x, y coordinate of the launcher private int dx; // speed of the missile launcher moving horizontally private int mx, my; // x, y coordinate of the missile // change mx, my into an array if desired, but add // an int called numMissiles private int score; // add a spaceship to shoot at (ex, ey for its x,y, edx, edy for its motion) private Timer t; public GraphicsPanel() { x=X_SIZE/2-5;y=740; // location of missile launcher dx=0; // launcher not moving to start mx=-1; // no missile currently in flight my=-1; // randomly place the enemy spaceship and its motion score=0; addKeyListener(this); t=new Timer(10, this); t.start(); } public void actionPerformed(ActionEvent e) { // move the launcher x+=dx; if(x>X_SIZE-30) dx=0; else if(x<30) dx=0; // if the missile is launched, move it if(mx!=-1) { my=my-4; if(my<10) { mx=-1; my=-1; } // once moved, check to make sure the missile // is still on the screen, if not reset mx and my to -1 // also check to see if mx, my has touched the enemy ship // if so, add 1 to score and change the location of the ship } // move the enemy ship, randomly change its direction occasionally // (see the Spaceship1.java program) repaint(); } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void keyPressed(KeyEvent e) { // get the key entered and determine if // you should change dx (for instance, moving // left might do dx=dx-1; and moving right // might do dx=dx+1; but do not like dx // become < -3 or > +3 or it will move too fast // enter key will stop the launcher (dx=0) if(e.getKeyCode()==KeyEvent.VK_LEFT) { dx--; if(dx<-3) dx=-3; } if(e.getKeyCode()==KeyEvent.VK_RIGHT) { dx++; if(dx>3) dx=3; } if(e.getKeyCode()==KeyEvent.VK_DOWN) { dx=0; } if(e.getKeyCode()==KeyEvent.VK_SPACE&&mx==-1) { mx=x; my=y; } } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); g.fillRect(0,0,X_SIZE,Y_SIZE); g.setColor(Color.red); g.drawLine(x,y,x+5,y+5); g.drawLine(x,y,x-5,y+5); g.drawLine(x+5,y+5,x-5,y+5); g.setColor(Color.white); g.drawLine(mx,my,mx,my-2); // draw the missile launcher // draw the missile(s) (if any) // draw the enemy ship // output the score } } }