Im trying to make a breakout game. I cant seem get the score to show up, but I was able to get everything else working.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PongPanel extends JPanel implements ActionListener
{
private Paddle paddle = new Paddle();
private PongBall ball = new PongBall(250, 200);
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setSize(806, 733);
f.add(new PongPanel());
f.setVisible(true);
}
public PongPanel()
{
setFocusable(true);
addKeyListener(paddle);
ball.addPaddle(paddle);
Timer metronome = new Timer(50, this);
metronome.start();
}
public void paintComponent(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(0, 0, 800, 700);
g.setColor(Color.black);
g.fillRect(40, 40, 720, 640);
g.setColor(Color.green);
g.fillRect(50, 50, 700, 600);
ball.paintBall(g);
paddle.paintPaddle(g);
g.setColor(Color.white);
g.drawString("Score: " + PongBall.getScore(), 75, 670);
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
import java.awt.*;
import java.awt.event.*;
public class PongBall
{
private int x = 0;
private int y = 0;
private int xVel = 10;
private int yVel = 10;
private Paddle paddle;
private int score = 0;
public int getScore()
{
return score;
}
public PongBall(int xStart, int yStart)
{
x = xStart;
y = yStart;
}
public void paintBall(Graphics g)
{
updatePosition();
g.setColor(Color.white);
g.fillOval(x - 10, y - 10, 20, 20);
}
public void addPaddle(Paddle p)
{
paddle = p;
}
private void updatePosition()
{
x = x + xVel;
y = y + yVel;
if(x < 60)
{
xVel = Math.abs(xVel);
x = 60;
}
if(y < 60)
{
yVel = Math.abs(yVel);
y = 60;
}
if(x > 740)
{
xVel = -Math.abs(xVel);
x = 740;
}
if(y > 610)
{
if(paddle.getX()-40 < x && paddle.getX()+40 > x)
{
yVel = -Math.abs(yVel);
y = 610;
}
else
{
x = 250;
y = 200;
}
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Paddle implements KeyListener
{
private int x = 0;
private int y = 620;
private int xVel = 0;
public int getX()
{
return x;
}
public void paintPaddle(Graphics g)
{
updatePosition();
g.setColor(Color.yellow);
g.fillRect(x-40, y-5, 100, 10);
}
private void updatePosition() //sets how far left and right the paddle can move
{
x = x + xVel;
if(x > 685)
{
x = 685;
}
if(x < 95)
{
x = 95;
}
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
xVel = -25;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
xVel = 25;
}
}
public void keyReleased(KeyEvent e)
{
xVel = 0;
}
public void keyTyped(KeyEvent e)
{}
}