// CS 134 demo to play the game of Pong
// This version constrains the paddle to stay in court boundary
import objectdraw.*;
import java.awt.*;
public class Pong3 extends WindowController{
// position and dimensions of the court
private static final int COURT_LEFT = 50,
COURT_TOP = 50,
COURT_HEIGHT = 300,
COURT_WIDTH = 250;
// dimensions of the paddle
private static final int PADDLE_WIDTH = 50,
PADDLE_HEIGHT = 20;
private FilledRect paddle; // paddle shape
private FramedRect boundary; // the boundary of the playing area.
// make the playing area and paddle
public void begin()
{
boundary = new FramedRect(COURT_LEFT, COURT_TOP,
COURT_WIDTH, COURT_HEIGHT,
canvas);
paddle =
new FilledRect(COURT_LEFT + (COURT_WIDTH-PADDLE_WIDTH)/2,
COURT_TOP + COURT_HEIGHT - PADDLE_HEIGHT -1,
PADDLE_WIDTH, PADDLE_HEIGHT,
canvas);
}
// make a new ball when the player clicks
public void onMouseClick(Location point)
{
new MovingBall(canvas, paddle, boundary);
}
// Move paddle in response to mouse move.
// Make sure it stays in the court
public void onMouseMove(Location point)
{
if ( point.getX() < COURT_LEFT )
{
// off left side - place paddle at left edge of the court
paddle.moveTo( COURT_LEFT,
COURT_TOP + COURT_HEIGHT - PADDLE_HEIGHT -1);
}
else if ( point.getX() > COURT_LEFT + COURT_WIDTH - PADDLE_WIDTH)
{
// off right side - place paddle at right edge of the court
paddle.moveTo( COURT_LEFT + COURT_WIDTH - PADDLE_WIDTH,
COURT_TOP + COURT_HEIGHT - PADDLE_HEIGHT -1);
}
else
{
// keep the edge of the paddle lined up with the mouse
paddle.moveTo( point.getX(),
COURT_TOP + COURT_HEIGHT - PADDLE_HEIGHT -1);
}
}
}