// Source File Name: TennisGame.java
import java.awt.Container;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
class TennisGame
{
TennisGame()
{
}
public static void main(String args[])
{
JFrame jframe = new JFrame();
jframe.setTitle("Tennis");
jframe.setSize(640, 480);
jframe.setDefaultCloseOperation(3);
MyPanel mypanel = new MyPanel();
jframe.getContentPane().add(mypanel);
jframe.setVisible(true);
}
}
class MyPanel extends JPanel
implements Runnable, MouseMotionListener
{
Ball ball;
Racket racket;
boolean lose;
public MyPanel()
{
setBackground(Color.white);
addMouseMotionListener(this);
ball = new Ball(100, 100, 5, 3, 0, 0, 610, 430, 20);
racket = new Racket(300, 400, 100, 10);
lose = false;
Thread thread = new Thread(this);
thread.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
ball.forward();
// if( ... ){
// ball.bounce();
// }
// if(ball.getY() > racket.getY() + 10) {
// g.setColor(Color.black);
// g.drawString("You lose", 290, 220);
// lose = true;
// }
g.setColor(Color.red);
g.fillOval(ball.getX(), ball.getY(), ball.getDiameter(),
ball.getDiameter());
g.setColor(Color.gray);
g.fillRect(racket.getX(), racket.getY(), racket.getWidth(),
racket.getHeight());
}
public void mouseDragged(MouseEvent mouseevent)
{
}
public synchronized void mouseMoved(MouseEvent mouseevent)
{
racket.setX(mouseevent.getX());
}
public void run()
{
do
{
do
{
repaint();
try
{
Thread.sleep(10L);
}
catch(Exception exception) { }
} while(!lose);
try
{
Thread.sleep(5000L);
}
catch(Exception exception1) { }
System.exit(0);
} while(true);
}
}
class Ball
{
private int x;
private int y;
private int vx;
private int vy;
private int left;
private int right;
private int top;
private int bottom;
private int diameter;
public Ball(int i, int j, int k, int l, int i1, int j1, int k1,
int l1, int i2)
{
x = i;
y = j;
vx = k;
vy = l;
right = k1;
left = i1;
top = j1;
bottom = l1;
diameter = i2;
}
public void forward()
{
x = x + vx;
y = y + vy;
if(x < left || x > right)
vx = -vx;
if(y < top || y > bottom)
vy = -vy;
}
public void bounce()
{
vy = -vy;
forward();
}
public int getX()
{
return x;
}
public void setX(int i)
{
x = i;
}
public int getY()
{
return y;
}
public void setY(int i)
{
y = i;
}
public int getDiameter()
{
return diameter;
}
}
class Racket
{
int x;
int y;
int width;
int height;
public Racket(int i, int j, int k, int l)
{
x = i;
y = j;
width = k;
height = l;
}
public void setX(int i)
{
x = i;
}
public int getX()
{
return x;
}
public void setY(int i)
{
y = i;
}
public int getY()
{
return y;
}
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
}