SlideShare a Scribd company logo
I need to be able to use the mouse COMP 274 Week 5 Lab Timer and Mouse Events and Java
Graphics Introduction The purpose of this weeks programming assignment is to learn how to
deal with events from multiple sources. In addition, we will learn how to use some of Javas
graphics capabilities for drawing shapes in a display area. The programming assignment for this
week is to implement a simple paddle ball game. Paddle Ball Game Overview The paddle ball
game is a simplification of the Pong game. In the Pong game, a ball is moving around the
display, bouncing off walls. The player moves a paddle in one dimension, trying to hit the ball
whenever possible. If the ball hits the paddle, it bounces off and continues on its way. If the
paddle misses the ball, the ball goes off the end of the display area and the player loses a point.
In our paddle ball game, the ball moves around the display, bouncing off walls just as in the
Pong game. The player controls a paddle trying to hit the ball just like in the Pong game. If the
ball hits the paddle, it bounces off and continues on its way. The main difference in our game is
that if the player misses the ball, the ball simply bounces off the wall behind the paddle and
continues to travel. There is no scoring in this game. Object Oriented Design If we analyze the
game description we can see there are several different objects which are interacting. There is a
ball object which is traveling around the display. There is a paddle object which is being moved
by the player. There is a display which is presenting the graphical representation of the game to
the user. These objects are readily apparent from the description of the game. The ball object has
a size and a position within the field of play. It also has a direction of travel in both the X and Y
dimensions. The ball must be able to update its position when needed. Since the ball normally
bounces off walls, it needs to know the length and width of the field of play when updating its
position. The ball must also be able to draw itself. The paddle has a size and a position within the
field of play. The paddle must be able to update its position within the field of play. The paddle
must also be able to draw itself. The display has a display area which has a length and width. It
has a means for drawing graphical shapes within the display area. The display area must be able
to update the display area the position of the ball or paddle changes. The display itself has no
concept of the game or its objects, so it will need to interact with some other object to draw all
the game objects. At this point, we have a ball, a paddle, and a display object. What is missing is
some object which provides the game context. The ball has no awareness of the paddle. The
paddle has no awareness of the ball. The display has no awareness of either the ball or paddle.
We need an object which enforces the rules and concepts of the game and manages the behaviors
of the other objects involved in the game. Lets call this the controller object. The controller has a
ball, a paddle, and a display object. The controller manages game events. It gets mouse events
and tells the paddle to update its position based on the position of the mouse cursor. It gets timer
events and tells the ball to update its position based on the size of the display area which it gets
from the display. It tells the display when to redraw the display area. It also provides a method
which the display object uses to request the controller to draw the current state of the game. The
controller is responsible for telling the ball and paddle to draw themselves. The controller is also
responsible for detecting when game objects are interacting. Specifically, it must be able to
determine when the ball has made contact with the paddle. This requires that the controller is
able to determine if a specific surface of the ball is in contact with a specific surface of the
paddle. When this is detected, the controller tells the ball to reverse the direction of travel in the
X or Y direction. This places a requirement on the ball and paddle to provide methods allowing
the controller to determine the X or Y position of any given surface of the ball or paddle. The
Ball Class Given that the ball has a size, a position, and moves a specific amount on each update,
the Ball class will need member variables for all of these attributes. The size of the ball
(diameter) and the number of pixels to move per update should be established when a ball object
is created (explicit value constructor). To simplify things, the distance to move (increment) will
initially be the same in the X and Y directions. The X and Y position members need to be set to
some starting position by the constructor. The X, Y position of the ball is the upper left corner of
the minimal box which contains the ball. When the X increment is positive, the ball is traveling
to the right. When it is negative it is traveling to the left. When the Y increment is positive the
ball is traveling down. When it is negative it is traveling up. According to the description in the
previous section, the ball must provide the position of its edges to the controller. To do that, the
Ball class provides the following methods: getTop, getBottom, getLeft, getRight The first two
methods return the Y coordinate of the top/bottom edge of the ball. The other two methods return
the X coordinate of the left/right edge of the ball. These values can easily be calculated from the
X, Y position and the diameter of the ball. The Ball class must provide a method which takes a
Graphics object parameter and uses it to draw the ball at its current position. When the controller
detects that the ball has hit the paddle, the controller must tell the ball to reverse its direction of
travel in either the X or Y direction. To be flexible, the Ball class should provide two methods,
one to reverse the X direction and one to reverse the Y direction. To the ball, reversing direction
simply means negating the value of the X or Y increment. The controller also must know
whether the center of the ball is within the boundaries of the paddle in order to detect contact.
This means the Ball class must provide methods to report its horizontal or vertical center. This
can be easily computed from the current position and the diameter. Finally, the Ball class
provides a method which the controller calls any time the ball needs to change position. This
method adds the X increment to the current X position, and the Y increment to the current Y
position. The Ball class is responsible for detecting when it has encountered a wall. So, this
method needs to know where the edges of the game area are. This method must be given the
length and height of the game area as parameters. The following conditions must be checked for
detecting contact with a wall: 1. Top edge of ball <= 0 then reverse Y travel direction 2. Bottom
edge of ball >= height then reverse Y travel direction 3. Left edge of ball <= 0 then reverse X
travel direction 4. Right edge of ball >= length then reverse X travel direction The Paddle Class
The Paddle class has a length and a position. Both of these should be initialized by an explicit
value constructor. That allows the controller to determine the paddle length and the position of
the paddle relative to the wall. We will simplify things by stating that the paddle will have a
horizontal orientation and will move left to right only. The paddle cannot move in the vertical
direction once it has been created. The X and Y position of the paddle should represent the center
of the top surface of the paddle. This will support the correlation of the mouse cursor position to
the center of the paddle. The draw method of the Paddle class takes a Graphics object parameter
and draws a filled rectangle based on the current position of the paddle. Drawing a rectangle is
based on the upper left corner of the rectangle as its reference position. Calculation of the
reference position is easily done using the X and Y position of the paddle and the length of the
paddle. The Paddle class controls what the width of the paddle will be. To support the controller,
the Paddle class must have methods which return the position of the top, bottom, left, and right
edges of the paddle. The controller needs this information for detecting when the ball and paddle
come into contact. The getTop and getBottom methods return a Y position. The getLeft and
getRight methods return an X position. These values are easily calculated from the X and Y
postion, and the length and width of the paddle. Finally, a method must be provided to allow the
controller to change the position of the paddle based on the X and Y coordinates of the mouse
cursor. This method must restrict the movement of the paddle to changes to the X coordinate
only. The Display Class The Display class provides a window to present the visual rendering of
the state of the game. It also must interact with the controller. The easiest way to create a Display
class which can draw various graphics is to have the class extend the JPanel class and override
the paintComponent method. This method should simply fill a rectangle with some background
color. The size of the rectangle is simply the size of the panel which is acquired from the
getWidth and getHeight methods of the JPanel class. After drawing the background, the display
object must pass its Graphics object to the controller, enabling the controller to arrange for the
other game components to draw themselves. The only other method needed in this class is an
explicit value constructor which takes a controller object and stores it into a member variable.
The constructor also creates a JFrame object storing it into a member variable. The display object
adds itself to the JFrame. The frame initialization should be completed, including setting the
initial size of the window which will display the game. The Controller Class The controller
manages all aspects of the game including various game parameters. It determines the diameter
of the ball and the distance the ball travels with each move. The distance travelled should be less
than the diameter. The speed of ball movement is controlled by a combination of distance
travelled and frequency of timer events. Timer events should be set up to occur around every 25
milliseconds. The length of the paddle should be at least twice the diameter of the ball. The game
is to be set up so the paddle moves horizontally near the top of the display area. There should be
at least 5% of the display height between the paddle and the top of the display area. The
Controller class contains a ball object, a paddle object, and a display object. In addition, the
controller is responsible for managing the events that drive the game. Therefore, this class must
implement the ActionListener interface to deal with Timer events which drive the ball. It must
also implement the MouseMotionListener interface to cause the paddle to move based on mouse
movement. The constructor of this class creates the three objects mentioned above. It also must
create a Timer object which will fire every 25 milliseconds and send ActionEvents to the
controller objects actionPerformed method. The last thing the constructor needs to do is to
register the controller object as a mouseMotionListener on the display object. So, when the
mouse cursor moves across the display area, MouseEvents will be delivered to the
mouseDragged or mouseMoved methods of the controller object. The controller provides a draw
method which takes a Graphics object parameter and is called by the display object. This method
should check to see if the ball and paddle objects exist, and if they do, ask each object to draw
itself, passing the Graphics object into the draw methods of those objects. The mouseDragged
and mouseMoved methods are responsible for managing the padddle position. When a
MouseEvent occurs and one of these methods executes, the method uses its MouseEvent
parameter to get the current X and Y coordinates of the mouse cursor. These coordinates are
given to the update method of the paddle which adjusts the paddle position based on these new
coordinates. Once the paddle has been updated, the controller calls the repaint method on the
display object to cause the display to reflect the new position of the paddle. The controllers
actionPerformed method is responsible for causing the ball to move and detecting whether the
ball is in contact with the paddle. It calls the update method on the ball, passing in the width and
height of the display which it gets from the display object. To detect whether the ball has just
contacted the paddle, the following steps should be executed: 1. Get the Y coordinates of the top
of the ball and the bottom of the paddle. 2. For contact to have just occurred, the top of the ball
must be less than or equal to the bottom of the paddle, and it must also be greater than or equal to
the bottom of the paddle minus the amount the ball just moved. 3. If step 2 is true, the horizontal
center of the ball must be between the left and right ends of the paddle. 4. If step 3 is true, tell the
ball to reverse its vertical direction. Finally, the actionPerformed method invokes the repaint
method to draw the display with the new position of the ball. Play the Game Create a test
application that creates a controller object and play the game! Experiment with changing the
game parameters and observe how the game reacts. When the game works, take a screen shot of
the game. Turn in ALL your code along with the screen shot. Make sure that your code is fully
commented!
Solution
The code for the paddle ball game can be written as follows:
Program:
import java.util.ArrayList;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; // get the timer functionality
public class DotsReboundPanel extends JPanel
{
private final int SIZE = 20; // radius of each dot
private Timer timer; // timer for our animation
private final int DELAY = 20; // 50 fps, 20 ms delay
private ArrayList pointList;
private int[] xvel = new int[1000], yvel = new int[1000]; // velocity x, y
private Color[] col = new Color[1000];
private int paddlex, paddley, paddlew, paddleh;
private int score=0, lives = 5;
//-----------------------------------------------------------------
// Constructor: Sets up this panel to listen for mouse events.
//-----------------------------------------------------------------
public DotsReboundPanel()
{
pointList = new ArrayList();
// initialize my velocity vectors
for (int i=0; i < 1000; i++)
{
xvel[i] = (int) (Math.random()*10-5);// random velocity between
yvel[i] = (int) (Math.random()*10-5);
col[i] = new Color(
(int)(Math.random()*255),
(int)(Math.random()*255),
(int)(Math.random()*255) );
}
timer = new Timer (DELAY, new DotTimeListener()); // create timer
addMouseListener (new DotsListener());
addMouseMotionListener (new DotsListener());
setBackground(Color.black);
setPreferredSize (new Dimension(300, 200));
timer.start(); // start timer
}
//-----------------------------------------------------------------
// Draws all of the dots stored in the list.
//-----------------------------------------------------------------
public void paintComponent (Graphics page)
{
super.paintComponent(page);
//paddlex = getWidth()/2; // starting paddle position
paddley = getHeight()-75;
paddlew = getWidth()/8;
paddleh = getHeight()/10;
int i=0;
for (Point spot : pointList)
{
page.setColor (col[i]);
page.fillOval (spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
i++;
}
page.setColor( Color.red );
page.drawString ("Score: " + score*i, 5, 15);
page.drawString ("Lives:" + lives, 60, 15);
i=0;
for (Point spot:pointList)
{
if ((spot.x > paddlex - paddlew/2 - SIZE) &&
(spot.x < paddlex + paddlew/2 + SIZE) &&
(spot.y >= paddley - SIZE) &&
(spot.y < paddley + SIZE) &&
(yvel[i] > 0))
{
yvel[i] = -(Math.abs(yvel[i]));
// add # of points to score
score++;
}
i++;
}
// draw a pong paddle
page.setColor(Color.white);
page.fillRect(paddlex-paddlew/2, paddley, paddlew, paddleh);
}
//*****************************************************************
// Represents the listener for mouse events.
//*****************************************************************
private class DotsListener implements MouseListener, MouseMotionListener
{
//--------------------------------------------------------------
// Adds the current point to the list of points and redraws
// the panel whenever the mouse button is pressed.
//--------------------------------------------------------------
public void mousePressed (MouseEvent event)
{
pointList.add(event.getPoint());
repaint();
}
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
@Override
public void mouseDragged(MouseEvent arg0) {
}
@Override
public void mouseMoved(MouseEvent event) {
// move the paddle to the x location of the mouse
paddlex = event.getX();
int i=0;
for (Point spot:pointList)
{
if ((spot.x > paddlex - paddlew/2 - SIZE) &&
(spot.x < paddlex + paddlew/2 + SIZE) &&
(spot.y >= paddley - SIZE) &&
(spot.y < paddley + SIZE) &&
(yvel[i] > 0))
{
yvel[i] = -(Math.abs(yvel[i]));
// add # of points to score
score++;
}
i++;
}
repaint();
}
}
//*****************************************************************
// Represents the action listener for the timer.
//*****************************************************************
private class DotTimeListener implements ActionListener
{
//--------------------------------------------------------------
// Move the dots in the pointList
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
int i=0;
for(Point spot : pointList)
{
spot.x += xvel[i];
spot.y += yvel[i];
// bounce my dots around
if ((spot.x+SIZE)>getWidth() || spot.x<0)
xvel[i] = -xvel[i];
if (spot.y<0)
yvel[i] = -yvel[i];
if (spot.y - SIZE >getHeight())
{
yvel[i] = -yvel[i];
// lose a life
lives--;
}
i++;
}
repaint();
}
}
}

More Related Content

Similar to I need to be able to use the mouse COMP 274 Week 5 Lab Timer and Mou.pdf

projectile-motion.ppt
projectile-motion.pptprojectile-motion.ppt
projectile-motion.ppt
MaRicaelaJamieFernan2
 
3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago
Janie Clayton
 
Darkonoid
DarkonoidDarkonoid
Darkonoid
graphitech
 
Lab 1 ball toss data analysis (physics with vernier experimen
Lab 1 ball toss data analysis (physics with vernier experimenLab 1 ball toss data analysis (physics with vernier experimen
Lab 1 ball toss data analysis (physics with vernier experimen
ADDY50
 
Python book
Python bookPython book
Python book
Victor Rabinovich
 
Up cloth - GameDesignDoccument
Up cloth - GameDesignDoccumentUp cloth - GameDesignDoccument
Up cloth - GameDesignDoccument
Eléonore Arbaux
 
Chess
ChessChess
2D Transformation.pdf
2D Transformation.pdf2D Transformation.pdf
2D Transformation.pdf
maheshshinde762539
 
Physics Ppt
Physics PptPhysics Ppt
Physics Pptd8r7z
 
fatima_hachem_Locating_the_Wii_remote_in_a_3_Dimensional_Field
fatima_hachem_Locating_the_Wii_remote_in_a_3_Dimensional_Field fatima_hachem_Locating_the_Wii_remote_in_a_3_Dimensional_Field
fatima_hachem_Locating_the_Wii_remote_in_a_3_Dimensional_Field Fatima Hachem
 
Vectors phy2 chp7
Vectors phy2 chp7Vectors phy2 chp7
Vectors phy2 chp7
Subas Nandy
 
Scratch for kids syllabus for 5 hours by bibek pandit
Scratch for kids syllabus for 5 hours by bibek panditScratch for kids syllabus for 5 hours by bibek pandit
Scratch for kids syllabus for 5 hours by bibek pandit
BibekPandit2
 
3D Transformation
3D Transformation3D Transformation
3D Transformation
Ahammednayeem
 
Virtual Trackball
Virtual TrackballVirtual Trackball
Virtual Trackball
Syed Zaid Irshad
 
Unit-3 overview of transformations
Unit-3 overview of transformationsUnit-3 overview of transformations
Unit-3 overview of transformations
Amol Gaikwad
 
GeoGebra 10
GeoGebra 10GeoGebra 10
GeoGebra 10
Boyd Hamulondo
 
K TO 12 GRADE 7 LEARNING MODULE IN SCIENCE (Q3-Q4)
K TO 12 GRADE 7 LEARNING MODULE IN SCIENCE (Q3-Q4)K TO 12 GRADE 7 LEARNING MODULE IN SCIENCE (Q3-Q4)
K TO 12 GRADE 7 LEARNING MODULE IN SCIENCE (Q3-Q4)
LiGhT ArOhL
 

Similar to I need to be able to use the mouse COMP 274 Week 5 Lab Timer and Mou.pdf (20)

projectile-motion.ppt
projectile-motion.pptprojectile-motion.ppt
projectile-motion.ppt
 
3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago3D Math Primer: CocoaConf Chicago
3D Math Primer: CocoaConf Chicago
 
Darkonoid
DarkonoidDarkonoid
Darkonoid
 
Pong analysis gs
Pong analysis gsPong analysis gs
Pong analysis gs
 
Lab 1 ball toss data analysis (physics with vernier experimen
Lab 1 ball toss data analysis (physics with vernier experimenLab 1 ball toss data analysis (physics with vernier experimen
Lab 1 ball toss data analysis (physics with vernier experimen
 
Python book
Python bookPython book
Python book
 
Up cloth - GameDesignDoccument
Up cloth - GameDesignDoccumentUp cloth - GameDesignDoccument
Up cloth - GameDesignDoccument
 
Chess
ChessChess
Chess
 
AI Lesson 07
AI Lesson 07AI Lesson 07
AI Lesson 07
 
2D Transformation.pdf
2D Transformation.pdf2D Transformation.pdf
2D Transformation.pdf
 
Physics Ppt
Physics PptPhysics Ppt
Physics Ppt
 
Ieeej 2010
Ieeej 2010Ieeej 2010
Ieeej 2010
 
fatima_hachem_Locating_the_Wii_remote_in_a_3_Dimensional_Field
fatima_hachem_Locating_the_Wii_remote_in_a_3_Dimensional_Field fatima_hachem_Locating_the_Wii_remote_in_a_3_Dimensional_Field
fatima_hachem_Locating_the_Wii_remote_in_a_3_Dimensional_Field
 
Vectors phy2 chp7
Vectors phy2 chp7Vectors phy2 chp7
Vectors phy2 chp7
 
Scratch for kids syllabus for 5 hours by bibek pandit
Scratch for kids syllabus for 5 hours by bibek panditScratch for kids syllabus for 5 hours by bibek pandit
Scratch for kids syllabus for 5 hours by bibek pandit
 
3D Transformation
3D Transformation3D Transformation
3D Transformation
 
Virtual Trackball
Virtual TrackballVirtual Trackball
Virtual Trackball
 
Unit-3 overview of transformations
Unit-3 overview of transformationsUnit-3 overview of transformations
Unit-3 overview of transformations
 
GeoGebra 10
GeoGebra 10GeoGebra 10
GeoGebra 10
 
K TO 12 GRADE 7 LEARNING MODULE IN SCIENCE (Q3-Q4)
K TO 12 GRADE 7 LEARNING MODULE IN SCIENCE (Q3-Q4)K TO 12 GRADE 7 LEARNING MODULE IN SCIENCE (Q3-Q4)
K TO 12 GRADE 7 LEARNING MODULE IN SCIENCE (Q3-Q4)
 

More from atulshingavi23680

I take 4 lures with me in my tackle box. I catch 8 distinct fish but.pdf
I take 4 lures with me in my tackle box. I catch 8 distinct fish but.pdfI take 4 lures with me in my tackle box. I catch 8 distinct fish but.pdf
I take 4 lures with me in my tackle box. I catch 8 distinct fish but.pdf
atulshingavi23680
 
I roll three fair dice independently. What is the probability the.pdf
I roll three fair dice independently.    What is the probability the.pdfI roll three fair dice independently.    What is the probability the.pdf
I roll three fair dice independently. What is the probability the.pdf
atulshingavi23680
 
I recently had a test and had this extra credit question. I really d.pdf
I recently had a test and had this extra credit question. I really d.pdfI recently had a test and had this extra credit question. I really d.pdf
I recently had a test and had this extra credit question. I really d.pdf
atulshingavi23680
 
I really, really like moderate inflation. I live in Sweden where the.pdf
I really, really like moderate inflation. I live in Sweden where the.pdfI really, really like moderate inflation. I live in Sweden where the.pdf
I really, really like moderate inflation. I live in Sweden where the.pdf
atulshingavi23680
 
I need to write a company report. The company I choose is Apple.Inc,.pdf
I need to write a company report. The company I choose is Apple.Inc,.pdfI need to write a company report. The company I choose is Apple.Inc,.pdf
I need to write a company report. The company I choose is Apple.Inc,.pdf
atulshingavi23680
 
I need some topics, points and a plan in probability and statistics .pdf
I need some topics, points and a plan in probability and statistics .pdfI need some topics, points and a plan in probability and statistics .pdf
I need some topics, points and a plan in probability and statistics .pdf
atulshingavi23680
 
i need to know the answer to 45 + 3 34 2 13 then simplify it sh.pdf
i need to know the answer to 45 + 3 34  2 13 then simplify it sh.pdfi need to know the answer to 45 + 3 34  2 13 then simplify it sh.pdf
i need to know the answer to 45 + 3 34 2 13 then simplify it sh.pdf
atulshingavi23680
 
I need the answer just to this question What stakeholder(s) did the.pdf
I need the answer just to this question What stakeholder(s) did the.pdfI need the answer just to this question What stakeholder(s) did the.pdf
I need the answer just to this question What stakeholder(s) did the.pdf
atulshingavi23680
 
I need this work out step by step so I can understand it. Chance.pdf
I need this work out step by step so I can understand it. Chance.pdfI need this work out step by step so I can understand it. Chance.pdf
I need this work out step by step so I can understand it. Chance.pdf
atulshingavi23680
 
I need solutions for the following questions.1.1.Simplify..pdf
I need solutions for the following questions.1.1.Simplify..pdfI need solutions for the following questions.1.1.Simplify..pdf
I need solutions for the following questions.1.1.Simplify..pdf
atulshingavi23680
 
I need help! I cannot get my excel sheet to work.Solution .pdf
I need help! I cannot get my excel sheet to work.Solution       .pdfI need help! I cannot get my excel sheet to work.Solution       .pdf
I need help! I cannot get my excel sheet to work.Solution .pdf
atulshingavi23680
 
I need help with this problem. I has several parts to be answered. I.pdf
I need help with this problem. I has several parts to be answered. I.pdfI need help with this problem. I has several parts to be answered. I.pdf
I need help with this problem. I has several parts to be answered. I.pdf
atulshingavi23680
 
I need short ans clear answer .USA has millions of individuals und.pdf
I need short ans clear answer .USA has millions of individuals und.pdfI need short ans clear answer .USA has millions of individuals und.pdf
I need short ans clear answer .USA has millions of individuals und.pdf
atulshingavi23680
 
i need sme information about etymology fr my math project Soluti.pdf
i need sme information about etymology fr my math project Soluti.pdfi need sme information about etymology fr my math project Soluti.pdf
i need sme information about etymology fr my math project Soluti.pdf
atulshingavi23680
 
I need help Write a sine function and a cosine function which ma.pdf
I need help Write a sine function and a cosine function which ma.pdfI need help Write a sine function and a cosine function which ma.pdf
I need help Write a sine function and a cosine function which ma.pdf
atulshingavi23680
 
I need some information on the relationship between the United State.pdf
I need some information on the relationship between the United State.pdfI need some information on the relationship between the United State.pdf
I need some information on the relationship between the United State.pdf
atulshingavi23680
 
I need some ideas on a power point presentation I have to make on el.pdf
I need some ideas on a power point presentation I have to make on el.pdfI need some ideas on a power point presentation I have to make on el.pdf
I need some ideas on a power point presentation I have to make on el.pdf
atulshingavi23680
 

More from atulshingavi23680 (17)

I take 4 lures with me in my tackle box. I catch 8 distinct fish but.pdf
I take 4 lures with me in my tackle box. I catch 8 distinct fish but.pdfI take 4 lures with me in my tackle box. I catch 8 distinct fish but.pdf
I take 4 lures with me in my tackle box. I catch 8 distinct fish but.pdf
 
I roll three fair dice independently. What is the probability the.pdf
I roll three fair dice independently.    What is the probability the.pdfI roll three fair dice independently.    What is the probability the.pdf
I roll three fair dice independently. What is the probability the.pdf
 
I recently had a test and had this extra credit question. I really d.pdf
I recently had a test and had this extra credit question. I really d.pdfI recently had a test and had this extra credit question. I really d.pdf
I recently had a test and had this extra credit question. I really d.pdf
 
I really, really like moderate inflation. I live in Sweden where the.pdf
I really, really like moderate inflation. I live in Sweden where the.pdfI really, really like moderate inflation. I live in Sweden where the.pdf
I really, really like moderate inflation. I live in Sweden where the.pdf
 
I need to write a company report. The company I choose is Apple.Inc,.pdf
I need to write a company report. The company I choose is Apple.Inc,.pdfI need to write a company report. The company I choose is Apple.Inc,.pdf
I need to write a company report. The company I choose is Apple.Inc,.pdf
 
I need some topics, points and a plan in probability and statistics .pdf
I need some topics, points and a plan in probability and statistics .pdfI need some topics, points and a plan in probability and statistics .pdf
I need some topics, points and a plan in probability and statistics .pdf
 
i need to know the answer to 45 + 3 34 2 13 then simplify it sh.pdf
i need to know the answer to 45 + 3 34  2 13 then simplify it sh.pdfi need to know the answer to 45 + 3 34  2 13 then simplify it sh.pdf
i need to know the answer to 45 + 3 34 2 13 then simplify it sh.pdf
 
I need the answer just to this question What stakeholder(s) did the.pdf
I need the answer just to this question What stakeholder(s) did the.pdfI need the answer just to this question What stakeholder(s) did the.pdf
I need the answer just to this question What stakeholder(s) did the.pdf
 
I need this work out step by step so I can understand it. Chance.pdf
I need this work out step by step so I can understand it. Chance.pdfI need this work out step by step so I can understand it. Chance.pdf
I need this work out step by step so I can understand it. Chance.pdf
 
I need solutions for the following questions.1.1.Simplify..pdf
I need solutions for the following questions.1.1.Simplify..pdfI need solutions for the following questions.1.1.Simplify..pdf
I need solutions for the following questions.1.1.Simplify..pdf
 
I need help! I cannot get my excel sheet to work.Solution .pdf
I need help! I cannot get my excel sheet to work.Solution       .pdfI need help! I cannot get my excel sheet to work.Solution       .pdf
I need help! I cannot get my excel sheet to work.Solution .pdf
 
I need help with this problem. I has several parts to be answered. I.pdf
I need help with this problem. I has several parts to be answered. I.pdfI need help with this problem. I has several parts to be answered. I.pdf
I need help with this problem. I has several parts to be answered. I.pdf
 
I need short ans clear answer .USA has millions of individuals und.pdf
I need short ans clear answer .USA has millions of individuals und.pdfI need short ans clear answer .USA has millions of individuals und.pdf
I need short ans clear answer .USA has millions of individuals und.pdf
 
i need sme information about etymology fr my math project Soluti.pdf
i need sme information about etymology fr my math project Soluti.pdfi need sme information about etymology fr my math project Soluti.pdf
i need sme information about etymology fr my math project Soluti.pdf
 
I need help Write a sine function and a cosine function which ma.pdf
I need help Write a sine function and a cosine function which ma.pdfI need help Write a sine function and a cosine function which ma.pdf
I need help Write a sine function and a cosine function which ma.pdf
 
I need some information on the relationship between the United State.pdf
I need some information on the relationship between the United State.pdfI need some information on the relationship between the United State.pdf
I need some information on the relationship between the United State.pdf
 
I need some ideas on a power point presentation I have to make on el.pdf
I need some ideas on a power point presentation I have to make on el.pdfI need some ideas on a power point presentation I have to make on el.pdf
I need some ideas on a power point presentation I have to make on el.pdf
 

Recently uploaded

special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
DhatriParmar
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 

Recently uploaded (20)

special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 

I need to be able to use the mouse COMP 274 Week 5 Lab Timer and Mou.pdf

  • 1. I need to be able to use the mouse COMP 274 Week 5 Lab Timer and Mouse Events and Java Graphics Introduction The purpose of this weeks programming assignment is to learn how to deal with events from multiple sources. In addition, we will learn how to use some of Javas graphics capabilities for drawing shapes in a display area. The programming assignment for this week is to implement a simple paddle ball game. Paddle Ball Game Overview The paddle ball game is a simplification of the Pong game. In the Pong game, a ball is moving around the display, bouncing off walls. The player moves a paddle in one dimension, trying to hit the ball whenever possible. If the ball hits the paddle, it bounces off and continues on its way. If the paddle misses the ball, the ball goes off the end of the display area and the player loses a point. In our paddle ball game, the ball moves around the display, bouncing off walls just as in the Pong game. The player controls a paddle trying to hit the ball just like in the Pong game. If the ball hits the paddle, it bounces off and continues on its way. The main difference in our game is that if the player misses the ball, the ball simply bounces off the wall behind the paddle and continues to travel. There is no scoring in this game. Object Oriented Design If we analyze the game description we can see there are several different objects which are interacting. There is a ball object which is traveling around the display. There is a paddle object which is being moved by the player. There is a display which is presenting the graphical representation of the game to the user. These objects are readily apparent from the description of the game. The ball object has a size and a position within the field of play. It also has a direction of travel in both the X and Y dimensions. The ball must be able to update its position when needed. Since the ball normally bounces off walls, it needs to know the length and width of the field of play when updating its position. The ball must also be able to draw itself. The paddle has a size and a position within the field of play. The paddle must be able to update its position within the field of play. The paddle must also be able to draw itself. The display has a display area which has a length and width. It has a means for drawing graphical shapes within the display area. The display area must be able to update the display area the position of the ball or paddle changes. The display itself has no concept of the game or its objects, so it will need to interact with some other object to draw all the game objects. At this point, we have a ball, a paddle, and a display object. What is missing is some object which provides the game context. The ball has no awareness of the paddle. The paddle has no awareness of the ball. The display has no awareness of either the ball or paddle. We need an object which enforces the rules and concepts of the game and manages the behaviors of the other objects involved in the game. Lets call this the controller object. The controller has a ball, a paddle, and a display object. The controller manages game events. It gets mouse events and tells the paddle to update its position based on the position of the mouse cursor. It gets timer events and tells the ball to update its position based on the size of the display area which it gets
  • 2. from the display. It tells the display when to redraw the display area. It also provides a method which the display object uses to request the controller to draw the current state of the game. The controller is responsible for telling the ball and paddle to draw themselves. The controller is also responsible for detecting when game objects are interacting. Specifically, it must be able to determine when the ball has made contact with the paddle. This requires that the controller is able to determine if a specific surface of the ball is in contact with a specific surface of the paddle. When this is detected, the controller tells the ball to reverse the direction of travel in the X or Y direction. This places a requirement on the ball and paddle to provide methods allowing the controller to determine the X or Y position of any given surface of the ball or paddle. The Ball Class Given that the ball has a size, a position, and moves a specific amount on each update, the Ball class will need member variables for all of these attributes. The size of the ball (diameter) and the number of pixels to move per update should be established when a ball object is created (explicit value constructor). To simplify things, the distance to move (increment) will initially be the same in the X and Y directions. The X and Y position members need to be set to some starting position by the constructor. The X, Y position of the ball is the upper left corner of the minimal box which contains the ball. When the X increment is positive, the ball is traveling to the right. When it is negative it is traveling to the left. When the Y increment is positive the ball is traveling down. When it is negative it is traveling up. According to the description in the previous section, the ball must provide the position of its edges to the controller. To do that, the Ball class provides the following methods: getTop, getBottom, getLeft, getRight The first two methods return the Y coordinate of the top/bottom edge of the ball. The other two methods return the X coordinate of the left/right edge of the ball. These values can easily be calculated from the X, Y position and the diameter of the ball. The Ball class must provide a method which takes a Graphics object parameter and uses it to draw the ball at its current position. When the controller detects that the ball has hit the paddle, the controller must tell the ball to reverse its direction of travel in either the X or Y direction. To be flexible, the Ball class should provide two methods, one to reverse the X direction and one to reverse the Y direction. To the ball, reversing direction simply means negating the value of the X or Y increment. The controller also must know whether the center of the ball is within the boundaries of the paddle in order to detect contact. This means the Ball class must provide methods to report its horizontal or vertical center. This can be easily computed from the current position and the diameter. Finally, the Ball class provides a method which the controller calls any time the ball needs to change position. This method adds the X increment to the current X position, and the Y increment to the current Y position. The Ball class is responsible for detecting when it has encountered a wall. So, this method needs to know where the edges of the game area are. This method must be given the length and height of the game area as parameters. The following conditions must be checked for
  • 3. detecting contact with a wall: 1. Top edge of ball <= 0 then reverse Y travel direction 2. Bottom edge of ball >= height then reverse Y travel direction 3. Left edge of ball <= 0 then reverse X travel direction 4. Right edge of ball >= length then reverse X travel direction The Paddle Class The Paddle class has a length and a position. Both of these should be initialized by an explicit value constructor. That allows the controller to determine the paddle length and the position of the paddle relative to the wall. We will simplify things by stating that the paddle will have a horizontal orientation and will move left to right only. The paddle cannot move in the vertical direction once it has been created. The X and Y position of the paddle should represent the center of the top surface of the paddle. This will support the correlation of the mouse cursor position to the center of the paddle. The draw method of the Paddle class takes a Graphics object parameter and draws a filled rectangle based on the current position of the paddle. Drawing a rectangle is based on the upper left corner of the rectangle as its reference position. Calculation of the reference position is easily done using the X and Y position of the paddle and the length of the paddle. The Paddle class controls what the width of the paddle will be. To support the controller, the Paddle class must have methods which return the position of the top, bottom, left, and right edges of the paddle. The controller needs this information for detecting when the ball and paddle come into contact. The getTop and getBottom methods return a Y position. The getLeft and getRight methods return an X position. These values are easily calculated from the X and Y postion, and the length and width of the paddle. Finally, a method must be provided to allow the controller to change the position of the paddle based on the X and Y coordinates of the mouse cursor. This method must restrict the movement of the paddle to changes to the X coordinate only. The Display Class The Display class provides a window to present the visual rendering of the state of the game. It also must interact with the controller. The easiest way to create a Display class which can draw various graphics is to have the class extend the JPanel class and override the paintComponent method. This method should simply fill a rectangle with some background color. The size of the rectangle is simply the size of the panel which is acquired from the getWidth and getHeight methods of the JPanel class. After drawing the background, the display object must pass its Graphics object to the controller, enabling the controller to arrange for the other game components to draw themselves. The only other method needed in this class is an explicit value constructor which takes a controller object and stores it into a member variable. The constructor also creates a JFrame object storing it into a member variable. The display object adds itself to the JFrame. The frame initialization should be completed, including setting the initial size of the window which will display the game. The Controller Class The controller manages all aspects of the game including various game parameters. It determines the diameter of the ball and the distance the ball travels with each move. The distance travelled should be less than the diameter. The speed of ball movement is controlled by a combination of distance
  • 4. travelled and frequency of timer events. Timer events should be set up to occur around every 25 milliseconds. The length of the paddle should be at least twice the diameter of the ball. The game is to be set up so the paddle moves horizontally near the top of the display area. There should be at least 5% of the display height between the paddle and the top of the display area. The Controller class contains a ball object, a paddle object, and a display object. In addition, the controller is responsible for managing the events that drive the game. Therefore, this class must implement the ActionListener interface to deal with Timer events which drive the ball. It must also implement the MouseMotionListener interface to cause the paddle to move based on mouse movement. The constructor of this class creates the three objects mentioned above. It also must create a Timer object which will fire every 25 milliseconds and send ActionEvents to the controller objects actionPerformed method. The last thing the constructor needs to do is to register the controller object as a mouseMotionListener on the display object. So, when the mouse cursor moves across the display area, MouseEvents will be delivered to the mouseDragged or mouseMoved methods of the controller object. The controller provides a draw method which takes a Graphics object parameter and is called by the display object. This method should check to see if the ball and paddle objects exist, and if they do, ask each object to draw itself, passing the Graphics object into the draw methods of those objects. The mouseDragged and mouseMoved methods are responsible for managing the padddle position. When a MouseEvent occurs and one of these methods executes, the method uses its MouseEvent parameter to get the current X and Y coordinates of the mouse cursor. These coordinates are given to the update method of the paddle which adjusts the paddle position based on these new coordinates. Once the paddle has been updated, the controller calls the repaint method on the display object to cause the display to reflect the new position of the paddle. The controllers actionPerformed method is responsible for causing the ball to move and detecting whether the ball is in contact with the paddle. It calls the update method on the ball, passing in the width and height of the display which it gets from the display object. To detect whether the ball has just contacted the paddle, the following steps should be executed: 1. Get the Y coordinates of the top of the ball and the bottom of the paddle. 2. For contact to have just occurred, the top of the ball must be less than or equal to the bottom of the paddle, and it must also be greater than or equal to the bottom of the paddle minus the amount the ball just moved. 3. If step 2 is true, the horizontal center of the ball must be between the left and right ends of the paddle. 4. If step 3 is true, tell the ball to reverse its vertical direction. Finally, the actionPerformed method invokes the repaint method to draw the display with the new position of the ball. Play the Game Create a test application that creates a controller object and play the game! Experiment with changing the game parameters and observe how the game reacts. When the game works, take a screen shot of the game. Turn in ALL your code along with the screen shot. Make sure that your code is fully
  • 5. commented! Solution The code for the paddle ball game can be written as follows: Program: import java.util.ArrayList; import javax.swing.JPanel; import java.awt.*; import java.awt.event.*; import javax.swing.*; // get the timer functionality public class DotsReboundPanel extends JPanel { private final int SIZE = 20; // radius of each dot private Timer timer; // timer for our animation private final int DELAY = 20; // 50 fps, 20 ms delay private ArrayList pointList; private int[] xvel = new int[1000], yvel = new int[1000]; // velocity x, y private Color[] col = new Color[1000]; private int paddlex, paddley, paddlew, paddleh; private int score=0, lives = 5; //----------------------------------------------------------------- // Constructor: Sets up this panel to listen for mouse events. //----------------------------------------------------------------- public DotsReboundPanel()
  • 6. { pointList = new ArrayList(); // initialize my velocity vectors for (int i=0; i < 1000; i++) { xvel[i] = (int) (Math.random()*10-5);// random velocity between yvel[i] = (int) (Math.random()*10-5); col[i] = new Color( (int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255) ); } timer = new Timer (DELAY, new DotTimeListener()); // create timer addMouseListener (new DotsListener()); addMouseMotionListener (new DotsListener()); setBackground(Color.black); setPreferredSize (new Dimension(300, 200)); timer.start(); // start timer } //----------------------------------------------------------------- // Draws all of the dots stored in the list. //----------------------------------------------------------------- public void paintComponent (Graphics page) { super.paintComponent(page); //paddlex = getWidth()/2; // starting paddle position paddley = getHeight()-75; paddlew = getWidth()/8; paddleh = getHeight()/10;
  • 7. int i=0; for (Point spot : pointList) { page.setColor (col[i]); page.fillOval (spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2); i++; } page.setColor( Color.red ); page.drawString ("Score: " + score*i, 5, 15); page.drawString ("Lives:" + lives, 60, 15); i=0; for (Point spot:pointList) { if ((spot.x > paddlex - paddlew/2 - SIZE) && (spot.x < paddlex + paddlew/2 + SIZE) && (spot.y >= paddley - SIZE) && (spot.y < paddley + SIZE) && (yvel[i] > 0)) { yvel[i] = -(Math.abs(yvel[i])); // add # of points to score score++; } i++; } // draw a pong paddle page.setColor(Color.white); page.fillRect(paddlex-paddlew/2, paddley, paddlew, paddleh);
  • 8. } //***************************************************************** // Represents the listener for mouse events. //***************************************************************** private class DotsListener implements MouseListener, MouseMotionListener { //-------------------------------------------------------------- // Adds the current point to the list of points and redraws // the panel whenever the mouse button is pressed. //-------------------------------------------------------------- public void mousePressed (MouseEvent event) { pointList.add(event.getPoint()); repaint(); } //-------------------------------------------------------------- // Provide empty definitions for unused event methods. //-------------------------------------------------------------- public void mouseClicked (MouseEvent event) {} public void mouseReleased (MouseEvent event) {} public void mouseEntered (MouseEvent event) {} public void mouseExited (MouseEvent event) {} @Override public void mouseDragged(MouseEvent arg0) { } @Override public void mouseMoved(MouseEvent event) { // move the paddle to the x location of the mouse
  • 9. paddlex = event.getX(); int i=0; for (Point spot:pointList) { if ((spot.x > paddlex - paddlew/2 - SIZE) && (spot.x < paddlex + paddlew/2 + SIZE) && (spot.y >= paddley - SIZE) && (spot.y < paddley + SIZE) && (yvel[i] > 0)) { yvel[i] = -(Math.abs(yvel[i])); // add # of points to score score++; } i++; } repaint(); } } //***************************************************************** // Represents the action listener for the timer. //***************************************************************** private class DotTimeListener implements ActionListener { //-------------------------------------------------------------- // Move the dots in the pointList //-------------------------------------------------------------- public void actionPerformed (ActionEvent event) {
  • 10. int i=0; for(Point spot : pointList) { spot.x += xvel[i]; spot.y += yvel[i]; // bounce my dots around if ((spot.x+SIZE)>getWidth() || spot.x<0) xvel[i] = -xvel[i]; if (spot.y<0) yvel[i] = -yvel[i]; if (spot.y - SIZE >getHeight()) { yvel[i] = -yvel[i]; // lose a life lives--; } i++; } repaint(); } } }