Stopping image movement - java

okay, so i have my image move straight down along the y axis whenever i click the mouse, my only problem is i don't know how to get it to stop when it hits the bottom of the screen, can someone please help?
import java.awt.Point;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class Control extends BasicGameState {
public static final int ID = 1;
public Methods m = new Methods();
public Point[] point = new Point[(800 * 600)];
int pressedX;
int pressedY;
int num = 0;
String Build = "1.1";
public void init(GameContainer container, StateBasedGame game) throws SlickException{
}
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
for (Point p : point) {
if (p != null) {
m.drawParticle(p.x, p.y += 1);
}
}
g.drawString("Particle Test", 680, 0);
g.drawString("Build: " + Build, 680, 15);
g.drawString("Pixels: " + num, 10, 25);
}
public void update(GameContainer container, StateBasedGame game, int delta) {
}
public void mousePressed(int button, int x, int y) {
pressedX = x;
pressedY = y;
num = num + 1;
point[num] = new Point(pressedX, pressedY);
}
public int getID() {
return ID;
}
}

I'd imagine somewhere you will want to check the x/y pos of the particle before you renderer it and remove it from the array when it's out of bounds...
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
for (int index = 0; index < point.length; index++) {
Point p = point[index];
if (p != null) {
p.y++;
if (p.y > height) { // You'll need to define height...
point[index] = null; // Or do something else with it??
} else {
m.drawParticle(p.x, p.y);
}
}
}
g.drawString("Particle Test", 680, 0);
g.drawString("Build: " + Build, 680, 15);
g.drawString("Pixels: " + num, 10, 25);
}
You could also do a preemptive check, which would allow you to know what points are at the bottom of the screen...
if (p != null) {
if (p.y >= height) { // You'll need to define height...
// Do something here
} else {
p.y++;
m.drawParticle(p.x, p.y);
}
}

Related

java jpanel how to optimise painting

I am trying to implement langton's ant , and i did it well :
langton's ant java simulation screen
for painting in my jPanel, i override the paintComponent at each step but it take so much time for painting every black or white rectangle , i just want that at each step i only paint the two rectangle who have changed!?
So my question is, how to only paint a rectangle without changing what was painted in previous frame?
here is my code for painting
public void paintComponent(Graphics g){
g.setColor(Color.white);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(Color.black);
int careLargeur = getWidth() / m;
int careHauteur = getHeight() / n;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
if(map[i][j])
g.fillRect(j*careLargeur,i*careHauteur,careLargeur,careHauteur);
}
//draw fourmi
g.setColor(Color.red);
g.fillOval(jF*careLargeur, iF*careHauteur, careLargeur, careHauteur);
}
any help? or should i give more details ?
here is the jar :
Paint your rectangles to a BufferedImage, and then draw that BufferedImage within your paintComponent method. You could also limit how much is re-drawn by using one of the repaint(...) overrides that specifies the exact rectangular region to repaint.
So your paintComponent method could be as simple as this:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
}
g.setColor(Color.red);
g.fillOval(jF*careLargeur, iF*careHauteur, careLargeur, careHauteur);
}
With drawing changes being made to the img BufferedImage.
Assuming that you're using a Swing Timer to drive the state changes to your model, you could
change the model, and then
update the BufferedImage based on the model changes, and
call repaint(...) on only the updated region.
Incomplete code attempt.... not yet done!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
/**
* https://en.wikipedia.org/wiki/Langton%27s_ant
* https://stackoverflow.com/a/44930371/522444
* #author Pete
*
*/
public class LangtonsAnt {
private static final int TIMER_DELAY = 30;
private static void createAndShowGui() {
Model model = new Model(800);
View view = new View(800);
Controller controller = new Controller(model, view);
JFrame frame = new JFrame("Langtons Ant");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(view);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
controller.startTimer(TIMER_DELAY);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static class Model {
public static final String POINT = "point";
private SwingPropertyChangeSupport support = new SwingPropertyChangeSupport(this);
private int gridSize;
private boolean[][] grid; // false is white. Better to use enums
private Point oldValue;
private Point point; // ant location
public Model(int gridSize) {
this.gridSize = gridSize;
grid = new boolean[gridSize][gridSize];
int x = gridSize / 2;
int y = gridSize / 2;
setPoint(new Point(x, y));
}
public void setPoint(Point point) {
this.oldValue = this.point;
Point newValue = point;
this.point = point;
support.firePropertyChange(POINT, oldValue, newValue);
}
public Point getPoint() {
return point;
}
public boolean[][] getGrid() {
return grid;
}
public int getGridSize() {
return gridSize;
}
public void step() {
// first will hold relative new positions
int newX = 0;
int newY = 0;
boolean gridPoint = getGridPoint(point);
if (oldValue == null) {
newX = point.x;
newY = point.y - 1;
} else {
int dX = point.x - oldValue.x;
int dY = point.y - oldValue.y;
if (dX != 0) {
// from left or right
newY = dX > 0 ? 1 : -1; // assume "white" or false
newY = gridPoint ? -newY : newY; // if "black" then reverse
} else {
// from up or down
newX = dY > 0 ? -1 : 1; // assume "white" or false
newX = gridPoint ? -newX : newX; // if "black" then reverse
}
// convert from relative to absolute new positions
newX = point.x + newX;
newY = point.y + newY;
}
setGridPoint(point, !gridPoint);
setPoint(new Point(newX, newY));
}
public boolean getGridPoint(int x, int y) {
return grid[x][y];
}
public boolean getGridPoint(Point p) {
return getGridPoint(p.x, p.y);
}
public void setGridPoint(int x, int y, boolean b) {
grid[x][y] = b;
}
public void setGridPoint(Point p, boolean b) {
setGridPoint(p.x, p.y, b);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) {
support.addPropertyChangeListener(propertyName, l);
}
}
private static class Controller {
private Model model;
private View view;
private Timer timer;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
view.setAntImg(createAntImg());
model.addPropertyChangeListener(Model.POINT, new ModelListener());
}
private BufferedImage createAntImg() {
// trivial image for now
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
g.setColor(Color.RED);
g.fillRect(0, 0, 1, 1);
g.dispose();
return img;
}
public void startTimer(int delay) {
timer = new Timer(delay, new TimerListener());
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
model.step();
}
}
private class ModelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
// TODO Finish this.
// get the new point and old point
// translate model coord to view coord
// Change the state of the view's buffered image
// repaint the limited region that was changed
}
}
}
private static class View extends JPanel {
private static final Color BACKGROUND = Color.WHITE;
private BufferedImage gridImg;
private BufferedImage antImg;
private Point guiAntLocation;
private int pixelWidth;
public View(int pixelWidth) {
this.pixelWidth = pixelWidth;
gridImg = new BufferedImage(pixelWidth, pixelWidth, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = gridImg.createGraphics();
g2.setColor(BACKGROUND);
g2.fillRect(0, 0, pixelWidth, pixelWidth);
g2.dispose();
}
public int getPixelWidth() {
return pixelWidth;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (getGridImg() != null) {
g.drawImage(getGridImg(), 0, 0, this);
}
if (guiAntLocation != null && antImg != null) {
int x = guiAntLocation.x;
int y = guiAntLocation.y;
g.drawImage(antImg, x, y, this);
}
}
public void setGuiAntLocation(Point guiAntLocation) {
this.guiAntLocation = guiAntLocation;
}
public Point getGuiAntLocation() {
return guiAntLocation;
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || getGridImg() == null) {
return super.getPreferredSize();
}
return new Dimension(getGridImg().getWidth(), getGridImg().getHeight());
}
public BufferedImage getGridImg() {
return gridImg;
}
public void setGridImg(BufferedImage gridImg) {
this.gridImg = gridImg;
}
public void setAntImg(BufferedImage antImg) {
this.antImg = antImg;
}
}
}

using java to draw the shortest line and the longest line with different colors

I am trying to draw the shortest line that I draw with a different color (green) and the longest line that I draw with another (white). How can I do that? Should I use if else statement?
And even if I do that I can make it nearest to 0 to print a different color I guess but that makes no sense when the line is actually zero.
import java.util.ArrayList;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class DotsPanel extends JPanel
{
private final int SIZE = 6; // radius of each dot
private int selectedCircle = -1;
private int length = 0;
private int i = 0;
private int totalDistance = 0;
private ArrayList<PointCount> pointList;
public DotsPanel()
{
pointList = new ArrayList<PointCount>();
addMouseListener (new DotsListener());
addMouseMotionListener (new DotsListener());
setBackground(Color.black);
setPreferredSize(new Dimension(300, 300));
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int min = Integer.MAX_VALUE;
int minIndex = -1;
int max = -Integer.MAX_VALUE;
int maxIndex = -1;
for(i=0; i < pointList.size()-1;i++){
length = (int)Math.sqrt(Math.pow(pointList.get(i).x - pointList.get(i+1).x, 2)+
Math.pow(pointList.get(i).y - pointList.get(i+1).y, 2));
g.setColor(Color.cyan);
g.drawString("" + length,(pointList.get(i).x+pointList.get(i+1).x)/2, (pointList.get(i).y+pointList.get(i+1).y)/2);
}
totalDistance += length;
for(i=0; i < pointList.size()-1;i++){
g.setColor(Color.white);
g.drawLine(pointList.get(i).x,
pointList.get(i).y,
pointList.get(i+1).x,
pointList.get(i+1).y);
g.setColor(Color.blue);
g.fillOval(pointList.get(i+1).x-SIZE,
pointList.get(i+1).y-SIZE,
SIZE*2,
SIZE*2);
// --- Displays counts
g.setColor(Color.yellow);
g.drawString("" + pointList.get(i+1).getCount(),
pointList.get(i+1).x,
pointList.get(i+1).y);
}
for(i=0; i < pointList.size()-2; i++) {
int distance = (int) Math.sqrt(Math.pow(pointList.get(i).x - pointList.get(i+1).x, 2)+
Math.pow(pointList.get(i).y - pointList.get(i+1).y, 2));
if(distance > max) {
max = distance;
maxIndex = i;
g.setColor(Color.red);
g.drawLine(pointList.get(i).x,
pointList.get(i).y,
pointList.get(i+1).x,
pointList.get(i+1).y);
}
if(distance < min) {
min = distance;
minIndex = i;
g.setColor(Color.green);
g.drawLine(pointList.get(i).x,
pointList.get(i).y,
pointList.get(i+1).x,
pointList.get(i+1).y);
}
}
g.setColor(Color.white);
g.drawString("Count: " + pointList.size(), 5, 15);
g.drawString("Total Distance: " + totalDistance, 5, 30);
}
private class DotsListener implements MouseListener,MouseMotionListener
{
public void mouseClicked(MouseEvent event)
{
boolean spotSelected = false;
int count = 0;
while(count < pointList.size() && !spotSelected) {
Point current = pointList.get(count).getPoint();
if(getDistance(event.getPoint(), current) <= SIZE) {
// --- Spot/circle selected or clicked on again
pointList.get(count).addCount();
spotSelected = false;
}
count++;
}
// --- Checks whether a new object needs to be created
if(!spotSelected) { // spotSelected == false
pointList.add(new PointCount(event.getPoint()));
}
repaint();
}
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mousePressed(MouseEvent e){}
public void mouseMoved(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
private int getDistance(Point p1, Point p2) {
return (int)Math.sqrt(Math.pow(p1.x - p2.x, 2)+
Math.pow(p1.y - p2.y, 2));
}
}
There are a few ways you could do this, this, for example, creates a simple Line class which is Comparable and which can calculate its own length. These are stored in a List which is sorted, so the shortest is first and the longest is last, making it a simple thing to pick them out of the List and paint them
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private List<Line> lines;
public TestPane() {
lines = new ArrayList<Line>(25);
MouseAdapter ma = new MouseAdapter() {
private Line currentLine;
#Override
public void mousePressed(MouseEvent e) {
currentLine = new Line(e.getPoint());
Collections.sort(lines);
lines.add(currentLine);
}
#Override
public void mouseReleased(MouseEvent e) {
currentLine = null;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
currentLine.to(e.getPoint());
Collections.sort(lines);
repaint();
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (!lines.isEmpty()) {
Line shortest = lines.get(0);
Line longest = lines.get(lines.size() - 1);
if (lines.size() > 2) {
lines.subList(1, lines.size() - 2);
for (Line line : lines) {
g2d.draw(line.getShape());
}
}
g2d.setColor(Color.RED);
g2d.draw(shortest.getShape());
if (!longest.equals(shortest)) {
g2d.setColor(Color.GREEN);
g2d.draw(longest.getShape());
}
}
g2d.dispose();
}
}
public class Line implements Comparable<Line> {
private Point p1;
private Point p2;
public Line(Point p1) {
this.p1 = p1;
this.p2 = p1;
}
public Line to(Point p) {
p2 = p;
return this;
}
public double getLength() {
return Math.sqrt(((p2.x - p1.x) * (p2.x - p1.x)) + ((p2.y - p1.y) * (p2.y - p1.y)));
}
#Override
public int compareTo(Line o) {
return (int) (getLength() - o.getLength());
}
public Line2D getShape() {
return new Line2D.Double(p1, p2);
}
}
}
Update
You need to determine the shortest/longest lines BEFORE you paint them, it's too late once you've started.
One way is to calculate the longest and shortest lengths when you add a new point, for example...
private class DotsListener implements MouseListener, MouseMotionListener {
public void mouseClicked(MouseEvent event) {
boolean spotSelected = false;
int count = 0;
while (count < pointList.size() && !spotSelected) {
Point current = pointList.get(count).getPoint();
if (getDistance(event.getPoint(), current) <= SIZE) {
// --- Spot/circle selected or clicked on again
pointList.get(count).addCount();
spotSelected = false;
}
count++;
}
// --- Checks whether a new object needs to be created
if (!spotSelected) { // spotSelected == false
pointList.add(new PointCount(event.getPoint()));
if (pointList.size() > 1) {
// Here, you now need to determine if the distance between the this and
// the previous point is the shortest or longest
longest = Math.max(longest, getDistance(pointList.get(pointList.size() - 1), pointList.get(pointList.size() - 2)));
shortest = Math.min(shortest, getDistance(pointList.get(pointList.size() - 1), pointList.get(pointList.size() - 2)));
}
}
repaint();
}
Then when you paint the lines, you'd just calculate the distance between each point and determine if they are the same length of as the longest or shortest lines...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int min = Integer.MAX_VALUE;
int minIndex = -1;
int max = -Integer.MAX_VALUE;
int maxIndex = -1;
for (i = 0; i < pointList.size() - 1; i++) {
length = (int) Math.sqrt(Math.pow(pointList.get(i).x - pointList.get(i + 1).x, 2)
+ Math.pow(pointList.get(i).y - pointList.get(i + 1).y, 2));
g.setColor(Color.cyan);
g.drawString("" + length, (pointList.get(i).x + pointList.get(i + 1).x) / 2, (pointList.get(i).y + pointList.get(i + 1).y) / 2);
}
totalDistance += length;
for (i = 0; i < pointList.size() - 1; i++) {
Point from = pointList.get(i);
Point to = pointList.get(i + 1);
int distance = getDistance(from, to);
if (distance == longest) {
g.setColor(Color.WHITE);
} else if (distance == shortest) {
g.setColor(Color.GREEN);
} else {
g.setColor(Color.BLACK);
}
//...

Image mouse hover error

my problem is that whenever I try to change an image when a mouse is hovered over it, it doesn't change, and when I do playgame.destroy(); it just shows a white screen behind it, not the other image. Heres my code:
import org.lwjgl.input.Mouse;
import org.newdawn.slick.*;
import org.newdawn.slick.state.*;
public class Menu extends BasicGameState {
Image playgame;
Image exitgame;
Image playgame_hover;
Image exitgame_hover;
public String mouse = "No Input Yet!";
public Menu(int state) {
}
#Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
playgame = new Image("res/playgame.png");
exitgame = new Image("res/exitgame.png");
playgame_hover = new Image("res/playgame_hover.png");
exitgame_hover = new Image("res/exitgame_hover.png");
}
#Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawString(mouse, 590, 10);
playgame.draw(100,100);
exitgame.draw(100, 200);
}
#Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int mousex = Mouse.getX();
int mousey = Mouse.getY();
mouse = "Mouse coordinate x: " + mousex + " y: " + mousey;
// x-min:105 x-max:300 y-min: y-max:300
if(input.isMouseButtonDown(0)) {
if((mousex>100 && mousex<600) && (mousey>357 && mousey<437)) {
sbg.enterState(1);
}
if((mousex>100 && mousex<600) && (mousey>257 && mousey <337)) {
System.exit(0);
}
}
if((mousex>100 && mousex<600) && (mousey>357 && mousey<437)) {
playgame.destroy();
playgame_hover.draw(100, 100);
}
if((mousex>100 && mousex<600) && (mousey>257 && mousey <337)) {
exitgame.destroy();
exitgame_hover.draw(100, 200);
}
}
#Override
public int getID() {
return 0;
}
}
You can only draw things in the render method. You have to save the state changed in the update method and then read those states in the render method.

Particle system Array

so I've been working on getting my boxes to save their position in an array all day and finally thought i came up with something (with a lot of help from you guys) and it just isn't working... can someone please tell me why?
Control class:
import java.awt.Point;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class Control extends BasicGameState {
public static final int ID = 1;
public Methods m = new Methods();
public Point[] point = new Point[(800 * 600)];
int pressedX;
int pressedY;
int num = 0;
public void init(GameContainer container, StateBasedGame game) throws SlickException{
}
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
m.drawParticle(pressedX, pressedY);
}
public void update(GameContainer container, StateBasedGame game, int delta) {
}
public void mousePressed(int button, int x, int y) {
pressedX = x;
pressedY = y;
num = num + 1;
point[num].x = pressedX;
point[num].y = pressedY;
}
public int getID() {
return ID;
}
}
Methods class:
import org.newdawn.slick.Graphics;
public class Methods {
public Graphics g = new Graphics();
public int sizeX = 1;
public int sizeY = 1;
public void drawParticle(float x, float y){
g.drawRect(x, y, sizeX, sizeY);
}
}
While you've initialised the size of the point array, you've not initialised the contents.
public void mousePressed(int button, int x, int y) {
pressedX = x;
pressedY = y;
num++;
point[num] = new Point(pressedX, pressedY);
}
Also think in your render method, you need to re-render the graphics (I could be mistaken, I've not used Slick2D before)...
Withing something like...
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
for (Point p : point) {
if (p != null) {
m.drawParticle(p.x, p.y);
}
}
m.drawParticle(pressedX, pressedY);
}
I'm also curious about you creating you're own Graphics, especially when the render method passes you one, you may want to check into that further and make sure that this is acceptable...

Three Paddle Pong Hit Detection

I am creating yet another version of pong. This one uses 3 paddles for each person. I have spent almost two hours trying to figure out why the two other paddles are not detecting when the ball strikes the paddle. The original (top) paddle does detect the hit and properly updates the hit counter. I have tried separate if statements, else if statements etc., with no success. I created three Y variables to detect the position of all three paddles still no luck.
Any suggestions?
import java.awt.Point;
public class box {
private int xTopLeft, yTopLeft, width, height;
int xBall, yBall;
private int radius = 5;
int xBallVel, yBallVel;
int VELOCITY_MAG =5;
public Point ballLoc = new Point();
private int paddleY;
private int paddleYP2;
private int paddleYP3;
private int paddleWidth = 20;
private int paddleWidth2 = 20;
private int paddleWidth3 = 20;
int hitCount = 0;
int missCount = 0;
private boolean updating=true;
public int getBallRadius()
{
return radius;
}
public Point getBallLoc()
{
ballLoc.x = xBall;
ballLoc.y = yBall;
return ballLoc;
}
public box(int x, int y, int w, int h)
{
xTopLeft =x;
yTopLeft = y;
width =w;
height = h;
createRandomBallLocation();
}
public void updatePaddle(int y)
{
paddleY = y;
}
public void updatePaddleP2(int yp2)
{
paddleYP2 = yp2;
}
public void updatePaddleP3(int yp3)
{
paddleYP3 = yp3;
}
public int getPaddleWidth()
{
return paddleWidth ;
}
public int getPaddleWidth2()
{
return paddleWidth2 ;
}
public int getPaddleWidth3()
{
return paddleWidth3 ;
}
public int getPaddleY()
{
System.out.println(paddleY);
return paddleY;
}
public int getPaddleP2()
{
System.out.println(paddleYP2);
return paddleYP2;
}
public int getPaddleP3()
{
return paddleYP3;
}
public int getHitCount()
{
return hitCount;
}
public int getMissCount()
{
return missCount;
}
public int velMag()
{
return VELOCITY_MAG;
}
public void update()
{
if (!updating) return;
xBall = xBall + xBallVel;
yBall = yBall + yBallVel;
if (xBall + radius >= xTopLeft+width && xBallVel>=0)
if ((yBall >= paddleY-paddleWidth && yBall <= paddleY + paddleWidth)
|| (yBall >= paddleYP2-paddleWidth2 && yBall <= paddleYP2 + paddleWidth2 )
|| (yBall >= paddleYP3-paddleWidth3 && yBall <= paddleYP3 + paddleWidth3 ))
{
// hit paddles
xBallVel = - xBallVel;
hitCount++;
}
else if (xBall+radius >= xTopLeft + width)
{
xBallVel = - xBallVel;
}
if (yBall+radius >= yTopLeft + height && yBallVel >= 0)
{
yBallVel = - yBallVel;
}
if (yBall-radius <= yTopLeft && yBallVel <=0)
{
yBallVel = - yBallVel;
}
if (xBall-radius <= xTopLeft && xBallVel <= 0)
{
xBallVel = - xBallVel;
}
}
public void createRandomBallLocation()
{
xBall = xTopLeft + radius +
(int)((width-2*radius)*Math.random());
yBall = yTopLeft + radius +
(int)((height-2*radius)*Math.random());
xBallVel = velMag();
yBallVel = velMag();
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.image.BufferStrategy;
public class Pong extends JFrame
implements Runnable{
box box = null;
int top, left, width, height;
final int LINE_THICKNESS = 5;
Graphics bufferGraphics;
int sleep=25;
public Pong(String name)
{
super(name);
int windowWidth = 1024;
int windowHeight =768;
this.setSize(windowWidth, windowHeight);
this.setResizable(false);
this.setLocation(400, 150);
this.setVisible(true);
this.createBufferStrategy(4);
MyMouseClick mmc = new MyMouseClick();
addMouseListener(mmc);
MyMouseMotion mmm = new MyMouseMotion();
addMouseMotionListener(mmm);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Thread thread = new Thread(this);
thread.start();
}
public void run()
{
while(true)
{
try
{
if (box != null)
{
box.update();
repaint();
}
Thread.sleep(sleep);
}
catch (InterruptedException e)
{}
}
}
public void paint(Graphics g)
{
BufferStrategy bf = this.getBufferStrategy();
g = bf.getDrawGraphics();
Dimension d = getSize();
if (box ==null)
{
Insets insets = getInsets();
left = insets.left;
top = insets.top;
width = d.width-left - insets.right;
height = d.height - top - insets.bottom;
box = new box(left, top, width, height);
}
g.fillRect(0,0, d.width, d.height);
g.setColor(Color.BLUE);
g.setFont(new Font("Arial", 20, 30));
g.drawString("Hits: "+box.getHitCount(), 20, 60);
g.setColor(Color.red);
g.setFont(new Font("Arial", 20, 30));
g.drawString("Misses: "+box.getMissCount(), 20, 380);
g.fillRect(left, top, left+width, LINE_THICKNESS); // top of box
g.setColor(Color.white);
g.fillRect(left, top+height, left+width, LINE_THICKNESS); // bottom of box
g.drawLine(left, top, left, top+height); // left of box
g.drawLine(left+width, top, left+width, top+height); // right side
Point ballLoc = box.getBallLoc();
int radius = box.getBallRadius();
g.fillOval(ballLoc.x - radius, ballLoc.y-radius, 2*radius, 2*radius);
// Draw paddles Player 1
g.setColor(Color.yellow);
int yp = box.getPaddleY();
int yp2 = box.getPaddleP2();
int yp3 = box.getPaddleP3();
int yw = box.getPaddleWidth();
int yw2 = box.getPaddleWidth2();
int yw3 = box.getPaddleWidth3();
g.fillRect(left+width-5, yp-yw, 4, 50);
g.fillRect(left+width-5, (yp2-yw2)+280, 4, 50);
g.fillRect(left+width-5, (yp3-yw3)+140, 4, 50);
bf.show();
}
// *********************** Inner classes
class MyMouseClick extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
box = null;
repaint();
}
}
class MyMouseMotion extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent e)
{
int y = e.getY();
int y2 = e.getY();
int y3 = e.getY();
if (box != null)
{
box.updatePaddle(y);
box.updatePaddleP2(y2);
box.updatePaddleP3(y3);
repaint();
}
}
}
// ************************************
public static void main(String[] args) {
Pong t = new Pong("Three Paddle Pong");
t.setVisible(true);
} // end of main
}
In the paint method you do paint your 3 paddles at different y positions, but for the actual paddle positions, paddleYP? which are used for collision detection, you just set the 3 paddles to the same y in mouseMoved.

Categories