import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TimerExample extends JApplet implements KeyListener { private Timer timer1; // propels top player horizontally across screen private Timer timer2; // propels bottom player horizontally across screen private Timer timerBullet2; // propels bottom player's bullet vertically up the screen private int x1; // the x location of top player private int x2; // the x location of bottom player private int bullet2Y; // the y location of bottom player's bullet private int bullet2X; // the x location of bottom player's bullet private int moveAmount1; // the top player's horizontal move amount in each timer step private int moveAmount2; // the bottom player's horizontal move amount in each timer step private int player2Score; public void init() { x1 = 0; x2 = 500; bullet2X = -10; bullet2Y = 180; addKeyListener(this); //instantiate each timer and give each its own "inner class" ActionListener timer1 = new Timer(200, new ActionListener() { public void actionPerformed(ActionEvent evt) { if (x1 <= 0) // right and left boundary collision detection { moveAmount1 = 10; } else if (x1 >= 500) { moveAmount1 = -10; } x1 += moveAmount1; // moving top player horizontally across screen repaint(); } }); timer2 = new Timer(200, new ActionListener() { public void actionPerformed(ActionEvent evt) { if (x2 <= 0) // right and left boundary collision detection { moveAmount2 = 10; } else if (x2 >= 500) { moveAmount2 = -10; } x2 += moveAmount2; // moving bottom player horizontally across screen repaint(); } }); timerBullet2 = new Timer(100, new ActionListener() { public void actionPerformed(ActionEvent evt) { if (bullet2X >= x1 && bullet2X <= x1 + 10 && bullet2Y <= 10 && bullet2Y >= 0) { player2Score++; } if (bullet2Y <= 10) // bullet boundary collision detection { timerBullet2.stop(); } bullet2Y -= 10; // moving bullet vertically up the screen repaint(); } }); } public void start() { timer1.start(); timer2.start(); } public void paint(Graphics g) { requestFocus(); g.setColor(Color.white); // covering over last player and bullet graphics g.drawRect(x1 - moveAmount1, 10, 20, 20); g.drawRect(x2 - moveAmount2, 200, 20, 20); g.drawLine(bullet2X, -20, bullet2X, 310); g.fillRect(20, 220, 60, 190); g.setColor(Color.black); // moving player and bullet graphics g.drawRect(x1, 10, 20, 20); g.drawRect(x2, 200, 20, 20); g.drawLine(bullet2X, bullet2Y, bullet2X, bullet2Y - 10); g.drawString("score: " + new Integer(player2Score).toString(), 30, 250); g.drawString("press spacebar to fire missile", 10, 280); } public void keyTyped(KeyEvent key) { if (key.getKeyChar() == ' ' && !timerBullet2.isRunning()) // space bar shoots missile { bullet2X = x2; bullet2Y = 180; timerBullet2.start(); } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } }