Game class not calling other classes - java

I am new to java code that is fresh code (I used to make minecraft mods) and I am trying to create a simple pong game. I have everything I believe I need for the game to play properly however it seems that the main game class is not calling the other classes when I need it to. Is there anything wrong here that you can see that I am missing? It would be a really great help.
Main Game Class
package crim.pong.main;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel{
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
Ball ball = new Ball(this);
Racquet racquet = new Racquet(this);
private void moveBall(){
ball.move();
racquet.move();
}
#Override
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 30, 30);
ball.paint(g2d);
racquet.paint(g2d);
}
public void gameOver(){
JOptionPane.showMessageDialog(this, "Game Over", "Game Over", JOptionPane.YES_NO_OPTION);
System.exit(ABORT);
}
public static void main(String[] args) throws InterruptedException{
JFrame frame = new JFrame("Pong");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while(true){
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
}
Keyboard class
package crim.pong.main;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class KeyboardInput extends JPanel{
public KeyboardInput(){
KeyListener listener = new MyKeyListener();
addKeyListener(listener);
setFocusable(true);
}
public static void main(String[] args){
JFrame frame = new JFrame("Pong");
KeyboardInput keyboardInput = new KeyboardInput();
frame.add(keyboardInput);
frame.setSize(200, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyKeyListener implements KeyListener{
#Override
public void keyTyped(KeyEvent e){
}
#Override
public void keyPressed(KeyEvent e){
System.out.println("keyPressed="+KeyEvent.getKeyText(e.getKeyCode()));
}
#Override
public void keyReleased(KeyEvent e){
System.out.println("keyReleased="+KeyEvent.getKeyText(e.getKeyCode()));
}
}
}
Ball class
package crim.pong.main;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Ball {
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
private Game game;
public Ball(Game game){
this.game = game;
}
void move(){
if(x + xa < 0)
xa = 1;
if(x + xa > game.getWidth() - DIAMETER)
xa = -1;
if(y + ya < 0)
ya = 1;
if(y + ya > game.getHeight() - DIAMETER)
game.gameOver();
if(collision()){
ya = -1;
y = game.racquet.getTopY() - DIAMETER;
}
x = x - xa;
y = y - ya;
}
private boolean collision(){
return game.racquet.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g){
g.fillOval(x, y, 30, 30);
}
public Rectangle getBounds(){
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
Racquet class
package crim.pong.main;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Racquet {
private static final int Y = 330;
private static final int WIDTH = 60;
private static final int HEIGHT = 20;
int x = 0;
int xa = 0;
private Game game;
public Racquet(Game game){
this.game = game;
}
public void move(){
if(x + xa > 0 && x + xa < game.getWidth() - 60)
x = xa + xa;
}
public void paint(Graphics2D g){
g.fillRect(x, 330, 60, 10);
}
public void keyReleased(KeyEvent e){
xa = 0;
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
}
public Rectangle getBounds(){
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
public int getTopY(){
return Y;
}
}

As mentioned in the comments you have 2 main class files. This is wrong.
A class with a 'main' function is the entry point of the program and obviously there can be only one entry point and presumably you have set this as 'Game'.
KeyboardInput should also not try to create a new JFrame. You only need one and it should be created by your 'Game' class.
If you want to keep the keyboard input in a seperate class then you want 'KeyboardInput' to implement KeyListener directly and then add it to the jframe created by 'Game', e.g.
(In 'Game')
KeyboardInput listener = new KeyboardInput();
addKeyListener(listener);
(In 'KeyboardInput')
public class KeyboardInput implements KeyListener
{
public void keyTyped(KeyEvent e){
//... etc etc

Related

KeyListener and ActionListener not registering

I have been working on a Java project that makes a character move with the keys, but the keyListener is not working and registering my actions. I code in eclipse, and I think that problem is my GamePanel, Player, or me KeyChecker class. I am using a guide to help start this, so it is the same code as another project, but it does not work. Here is my code:
class Platformer:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Platformer {
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setSize(700,700);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setTitle("Platformer");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class GamePanel:
I have tried changing the layout of the if statements if that was the original problem, but it did not change anything. I also tried changing the statements to just void instead of public void but that did not work either.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements ActionListener{
Player player;
ArrayList<Wall> walls = new ArrayList<>();
Timer gameTimer;
public GamePanel() {
player = new Player(400, 300, this);
makeWalls();
gameTimer = new Timer();
gameTimer.schedule(new TimerTask() {
public void run() {
player.set();
repaint();
}
},0,17);
}
public void makeWalls() {
for (int i = 50; i < 650; i += 50) {
walls.add (new Wall(i, 600, 50, 50));
}
walls.add(new Wall(50, 550, 50, 50));
walls.add(new Wall(50, 500, 50, 50));
walls.add(new Wall(50, 450, 50, 50));
walls.add(new Wall(600, 550, 50, 50));
walls.add(new Wall(600, 500, 50, 50));
walls.add(new Wall(600, 450, 50, 50));
walls.add(new Wall(450, 550, 50, 50));
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D gtd = (Graphics2D) g;
player.draw(gtd);
for (Wall wall: walls) wall.draw(gtd);
}
public void KeyPressed(KeyEvent e) {
if (e.getKeyChar() == 'a')player.keyLeft = true;
if (e.getKeyChar() == 'w') player.keyUp = true;
if (e.getKeyChar() == 's') player.keyDown = true;
if (e.getKeyChar() == 'd') player.keyRight = true;
}
public void KeyReleased(KeyEvent e) {
if (e.getKeyChar() == 'a') player.keyLeft = false;
if (e.getKeyChar() == 'w') player.keyUp = false;
if (e.getKeyChar() == 's') player.keyDown = false;
if (e.getKeyChar() == 'd') player.keyRight = false;
}
public void actionPerformed(ActionEvent e) {
}
}
class Player:
I also tried the same things that I did for the GamePanel, but that did not work either.
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Player {
GamePanel panel;
int x;
int y;
int width;
int height;
double xspeed;
double yspeed;
Rectangle hitBox;
boolean keyRight;
boolean keyLeft;
boolean keyUp;
boolean keyDown;
public Player(int x, int y, GamePanel panel) {
this.panel = panel;
this.x = x;
this.y = y;
width = 50;
height = 100;
hitBox = new Rectangle(x,y,width,height);
}
public void set() {
if (keyLeft && keyRight || !keyLeft && !keyRight) xspeed *= 0.8;
else if (keyLeft && !keyRight) xspeed --;
else if (keyRight && !keyLeft) xspeed ++;
if (xspeed > 0 && xspeed < 0.75) xspeed = 0;
if (xspeed < 0 && xspeed > - 0.75) xspeed = 0;
if (xspeed > 7) xspeed = 7;
if (xspeed < -7) xspeed = -7;
if (keyUp) {
hitBox.y++;
for(Wall wall: panel.walls) {
if (wall.hitBox.intersects(hitBox)) yspeed = -6;
}
hitBox.y --;
}
yspeed += .3;
hitBox.x += xspeed;
for(Wall wall: panel.walls) {
if (hitBox.intersects(wall.hitBox)) {
hitBox.x-= xspeed;
while(!wall.hitBox.intersects(hitBox)) hitBox.x += Math.signum(xspeed);
hitBox.x -= Math.signum(xspeed);
xspeed = 0;
x = hitBox.x;
}
}
hitBox.y += xspeed;
for(Wall wall: panel.walls) {
if (hitBox.intersects(wall.hitBox)) {
hitBox.y-= yspeed;
while(!wall.hitBox.intersects(hitBox)) hitBox.y += Math.signum(yspeed);
hitBox.y -= Math.signum(yspeed);
yspeed = 0;
y = hitBox.y;
}
}
x += xspeed;
y += yspeed;
hitBox.x = x;
hitBox.y = y;
}
public void draw(Graphics2D gtd) {
gtd.setColor(Color.BLACK);
gtd.fillRect(x, y, width, height);
}
}
class KeyChecker:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyChecker extends KeyAdapter{
GamePanel panel;
public KeyChecker(GamePanel panel) {
this.panel = panel;
}
public void KeyPressed(KeyEvent e) {
panel.KeyPressed(e);
}
public void KeyReleased(KeyEvent e) {
panel.KeyReleased (e);
}
}
class Wall:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Wall {
int x;
int y;
int width;
int height;
Rectangle hitBox;
public Wall (int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = width;
hitBox = new Rectangle(x, y, width, height);
}
public void draw(Graphics2D gtd) {
gtd.setColor(Color.BLACK);
gtd.drawRect(x, y, width, height);
gtd.setColor(Color.WHITE);
gtd.fillRect(x + 1, y + 1, width - 2, height - 2);
}
}
class MainFrame:
import java.awt.Color;
import javax.swing.JFrame;
public class MainFrame extends JFrame{
public MainFrame() {
GamePanel panel = new GamePanel();
panel.setLocation(0,0);
panel.setSize(this.getSize());
panel.setBackground(Color.LIGHT_GRAY);
panel.setVisible(true);
this.add(panel);
addKeyListener(new KeyChecker(panel));
}
}
Thank you for your help.
The functions in KeyChecker should start with lower case, so public void keyPressed and keyReleased.
In addition, you should add implements KeyListener to the classes KeyChecker and GamePanel (remove ActionListener in GamePanel).
Then, add the unimplemented functions. Eclipse will ask you for it.
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
Remark, it's better to #Override the functions keyPressed and keyReleased, rather than creating new functions.
I tried them, it worked!

Adding Start, Stop, Reset button to simple java game

I am a new coder. I am having trouble adding a start and stop button for this piece of example code that i am working off. I'm sure i have to mess with with Thread.sleep(10); in the game class. This code starts the game when the program is run. is there a way i could add start button to start the thread. I have created j button already. Thanks.
Game Class
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel {
Ball ball = new Ball(this);
Racquet racquet = new Racquet(this);
public Game() {
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
racquet.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
racquet.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
ball.move();
racquet.move();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
racquet.paint(g2d);
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "Game Over", "Game Over", JOptionPane.YES_NO_OPTION);
System.exit(ABORT);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Mini Tennis");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
}
Ball Class
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Ball {
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
private Game game;
public Ball(Game game) {
this.game= game;
}
void move() {
if (x + xa < 0)
xa = 1;
if (x + xa > game.getWidth() - DIAMETER)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > game.getHeight() - DIAMETER)
game.gameOver();
if (collision()){
ya = -1;
y = game.racquet.getTopY() - DIAMETER;
}
x = x + xa;
y = y + ya;
}
private boolean collision() {
return game.racquet.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g) {
g.fillOval(x, y, DIAMETER, DIAMETER);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
Racquet Class
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Racquet {
private static final int Y = 330;
private static final int WIDTH = 60;
private static final int HEIGHT = 10;
int x = 0;
int xa = 0;
private Game game;
public Racquet(Game game) {
this.game = game;
}
public void move() {
if (x + xa > 0 && x + xa < game.getWidth() - WIDTH)
x = x + xa;
}
public void paint(Graphics2D g) {
g.fillRect(x, Y, WIDTH, HEIGHT);
}
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
}
public Rectangle getBounds() {
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
public int getTopY() {
return Y;
}
}
This is an mcve demonstrating the structure outlined in Hovercraft Full Of Eels comment :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class AnimationUsingTimer {
private Timer timer;
AnimationUsingTimer() {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AnimationPanel animationPanel = new AnimationPanel();
window.add(animationPanel);
JButton start = new JButton("Start");
start.addActionListener(e -> animationPanel.start());
window.add(start, BorderLayout.PAGE_START);
JButton stop = new JButton("Stop");
stop.addActionListener(e -> animationPanel.stop());
window.add(stop, BorderLayout.PAGE_END);
window.pack();
window.setVisible(true);
}
class AnimationPanel extends JPanel{
private BufferedImage img;
private Area ball, walls;
private final static int W = 450, H = 300, DIAMETER = 20;
private int x = W/2, y = H/2, xDelta = 3, yDelta = 2;
AnimationPanel() {
img = new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
JLabel imageLabel = new JLabel(new ImageIcon(img));
add(imageLabel);
walls = new Area(new Rectangle(0,0,W,H));
ActionListener animate = e -> {
animate();
repaint();
};
timer = new Timer(50, animate);
}
public void animate() {
x+=xDelta; y+=yDelta;
ball = new Area(new Ellipse2D.Double(x, y, DIAMETER, DIAMETER));
if (checkCollision(ball,walls)) {
if ( x+DIAMETER>img.getWidth() || x<0 ) {
xDelta *= -1;
}
if(y+DIAMETER>img.getHeight() || y<0 ) {
yDelta *= -1;
}
}
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2D = img.createGraphics();
g2D.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2D.setColor(Color.CYAN);
g2D.fillRect(0, 0, img.getWidth(), img.getHeight());
if(ball != null){
g2D.setColor(Color.RED);
g2D.fill(ball);
}
g2D.dispose();
}
void start(){
timer.start();
}
void stop(){
timer.stop();
}
private boolean checkCollision(Area area1, Area area2) {
return area1.getBounds().intersects(area2.getBounds());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new AnimationUsingTimer());
}
}

Blank screen during the execution of a java application on the swing frame

I have the following three classes:
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
public class Racquet {
int x = 0;
int xa = 0;
private Game game;
public Racquet(Game game) {
this.game= game;
}
public void move() {
if (x + xa > 0 && x + xa < game.getWidth()-60)
x = x + xa;
}
public void paint(Graphics2D g) {
g.fillRect(x, 330, 60, 10);
}
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
}
}
import java.awt.Graphics2D;
public class Ball {
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
private Game game;
public Ball(Game game) {
this.game= game;
}
void move() {
if (x + xa < 0)
xa = 1;
if (x + xa > game.getWidth() - 30)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > game.getHeight() - 30)
ya = -1;
x = x + xa;
y = y + ya;
}
public void paint(Graphics2D g) {
g.fillOval(x, y, 30, 30);
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Game extends JPanel {
Ball ball = new Ball(this);
Racquet racquet = new Racquet(this);
public Game() {
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
racquet.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
racquet.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
ball.move();
racquet.move();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
racquet.paint(g2d);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Mini Tennis");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
for(long i=0;i<=100000*100;i++)
{
}
}
}
}
import javax.swing.*;
import java.awt.event.*;
class T extends JFrame implements ActionListener
{
public T()
{
setVisible(true);
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
JButton b1=new JButton("Click me");
b1.setBounds(150,150,50,50);
b1.addActionListener(this);
add(b1);
}
public void actionPerformed(ActionEvent a)
{
Game ob=new Game();
ob.main(null);
}
public static void main(String args[])
{
T obj=new T();
}
}
When I execute the class T, I am supposed to get the Game but I don't know why I get the blank screen and not the game. I am new to Java so could someone help me out?
The reason that the T class doesn't work is that your code uses bad code to run the game loop, a while (true) loop that if called on the Swing event thread (as T does), will completely block the this thread, preventing it from performing its necessary functions including drawing the GUI.
The solution is to use a Swing Timer to drive your game loop, not a while (true) loop. To gain a better understanding of Swing threading issues, please read: Lesson: Concurrency in Swing

Bouncing ball around edges using action listener

I am relatively new to java, i am trying to make an animation that when run the ball should move steadily around the enclosing rectangle, bouncing off the edges. When the STOP button is clicked the motion should freeze, and lastly when the GO button is pressed it should resume.
This is the code that i have produced so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
// Does the drawing
class MyDrawing extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.red);
Ellipse2D.Double circle = new Ellipse2D.Double(300,120,50,50);
g2.draw(circle);
g2.fill(circle);
Rectangle box1 = new Rectangle(10, 10, 380, 300);
g.setColor(Color.BLACK);
g2.draw(box1);
}
}
//Produces window plus everything inside it
public class ControlledBall extends JFrame {
JButton flash = new JButton("Go");
JButton steady = new JButton("Stop");
JPanel panel = new JPanel(new GridBagLayout());
MyDrawing drawing = new MyDrawing();
Timer timer;
public ControlledBall(){
panel.add(flash);
panel.add(steady);
this.add(panel,BorderLayout.SOUTH);
this.add(drawing,BorderLayout.CENTER);
steady.addActionListener(new SteadyListener());
flash.addActionListener(new MoveListener());
timer = new Timer(500, new MoveListener());
timer.start();
}
class MoveListener implements ActionListener{
public void actionPerformed(ActionEvent event){
timer.start();
move();
}
}
//Stuck what to implement here
class SteadyListener implements ActionListener{
public void actionPerformed(ActionEvent event){
}
}
public static void main(String[] args) {
JFrame window = new ControlledBall();
window.setSize(400,400);
window.setTitle("Controlled Ball");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void move() {
long delay = 40;}
private int x = 1;
private int y = 1;
private int dx = 3;
private int dy = 2;{
int dia = 30;
Color color = Color.red;
if(x + dx < 0 || x + dia + dx > getWidth()) {
dx *= -1;
color = Color.red;
}
if(y + dy < 0 || y + dia + dy > getHeight()) {
dy *= -1;
color = Color.red;
}
x += dx;
y += dy;
}
}
When i run the program this is my output but nothing happens:
As chiliNUT says, the x, y, dx, dy variables that keep direction and position must be class fields, not local variables.
You can add xPos, yPos fields to MyDrawing class to keep the ballĀ“s position
and dx ControlledBall class to keep direction, for instance:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
//Does the drawing
class MyDrawing extends JPanel {
private int xpos;
private int ypos;
public void setXPos(final int x) {
this.xpos = x;
}
public void setYPos(final int y) {
this.ypos = y;
}
public int getXpos() {
return xpos;
}
public int getYpos() {
return ypos;
}
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
final Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.red);
final Ellipse2D.Double circle = new Ellipse2D.Double(xpos, ypos, 50, 50);
g2.draw(circle);
g2.fill(circle);
final Rectangle box1 = new Rectangle(10, 10, 380, 300);
g.setColor(Color.BLACK);
g2.draw(box1);
}
}
// Produces window plus everything inside it
public class ControlledBall extends JFrame {
private final JButton flash = new JButton("Go");
private final JButton steady = new JButton("Stop");
private final JPanel panel = new JPanel(new GridBagLayout());
private final MyDrawing drawing = new MyDrawing();
private final Timer timer;
//direction
private int dx = 3;
private int dy = 2;
public ControlledBall() {
panel.add(flash);
panel.add(steady);
this.add(panel, BorderLayout.SOUTH);
this.add(drawing, BorderLayout.CENTER);
drawing.setXPos(300);
drawing.setYPos(150);
steady.addActionListener(new SteadyListener());
final MoveListener ml = new MoveListener();
flash.addActionListener(ml);
timer = new Timer(15, ml);
}
class MoveListener implements ActionListener {
#Override
public void actionPerformed(final ActionEvent event) {
if (!timer.isRunning()){
timer.start();
}
move();
}
}
// Stuck what to implement here
class SteadyListener implements ActionListener {
#Override
public void actionPerformed(final ActionEvent event) {
if (timer.isRunning()){
timer.stop();
}
}
}
private void move() {
int x = drawing.getXpos();
int y = drawing.getYpos();
final int dia = 30;
if (x + dx < 0 || x + dia + dx > getWidth()) {
dx *= -1;
}
if (y + dy < 0 || y + dia + dy > getHeight()) {
dy *= -1;
}
x += dx;
y += dy;
drawing.setXPos(x);
drawing.setYPos(y);
repaint();
}
public static void main(final String[] args) {
final JFrame window = new ControlledBall();
window.setSize(400, 400);
window.setTitle("Controlled Ball");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}

JAVA Bounding Box / Collison Detection

I am trying to build a basic Arcanoid/Breakout style game in JAVA. I am having trouble with the collision detection between the ball and the bricks. I am using bounding boxes around all entities in the game. When the ball hits the player's paddle, the collision is detected. When the ball hits the bricks coordinates, no collision is detected. Any one have any ideas. Code below.
Game.java
package com.seadnamcgillycuddy.unipong;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel {
Ball ball = new Ball(this);
Paddle paddle = new Paddle(this);
Brick brick = new Brick(this, 50, 20);
Brick brick2 = new Brick(this, 75, 20);
Brick brick3 = new Brick(this, 100, 20);
Brick brick4 = new Brick(this, 125, 20);
Brick brick5 = new Brick(this, 150, 20);
Brick brick6 = new Brick(this, 175, 20);
Brick brick7 = new Brick(this, 200, 20);
Brick brick8 = new Brick(this, 225, 20);
Brick brick9 = new Brick(this, 250, 20);
int speed = 1;
private int getScore() {
return speed - 1;
}
public Game() {
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
paddle.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
paddle.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
ball.move();
paddle.move();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
paddle.paint(g2d);
brick.paint(g2d);
brick2.paint(g2d);
brick3.paint(g2d);
brick4.paint(g2d);
brick5.paint(g2d);
brick6.paint(g2d);
brick7.paint(g2d);
brick8.paint(g2d);
brick9.paint(g2d);
g2d.setColor(Color.GRAY);
g2d.setFont(new Font("Verdana", Font.BOLD, 30));
g2d.drawString(String.valueOf(getScore()), 10, 30);
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "Your Score Is: " + getScore(), "Game Over", JOptionPane.YES_NO_OPTION);
System.exit(ABORT);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("UniPong");
Game game = new Game();
frame.add(game);
frame.setSize(400, 750);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true){
game.move();
game.repaint();
Thread.sleep(10);
}
}
}
Ball.java
package com.seadnamcgillycuddy.unipong;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Ball {
private static final int DIAMETER = 10;
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
private Game game;
public Ball(Game game) {
this.game = game;
}
void move() {
boolean changeDirection = true;
if (x + xa < 0)
xa = game.speed;
else if (brickCollision()){
System.out.println("Collission!!!!");
}
else if (x + xa > game.getWidth() - DIAMETER)
xa = -game.speed;
else if (y + ya < 0)
ya = game.speed;
else if (y + ya > game.getHeight() - DIAMETER)
game.gameOver();
else if (collision()) {
ya = -game.speed;
y = game.paddle.getTopY() - DIAMETER;
game.speed++;
} else
changeDirection = false;
x = x + xa;
y = y + ya;
}
private boolean collision() {
return game.paddle.getBounds().intersects(getBounds());
}
private boolean brickCollision() {
return game.brick.getBounds().intersects(getBounds());
//return game.ball.getBounds().intersects(getBounds());
}
public void paint (Graphics2D g) {
g.fillOval(x, y, DIAMETER, DIAMETER);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
Brick.java
package com.seadnamcgillycuddy.unipong;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Brick {
int Y;
int X;
private static final int WIDTH = 20;
private static final int HEIGHT = 10;
private Game game;
public Brick(Game game, int X, int Y) {
this.X = X;
this.Y = Y;
this.game = game;
}
public void paint(Graphics2D g) {
g.fillRect(X, Y, WIDTH, HEIGHT);
}
public Rectangle getBounds() {
return new Rectangle(X, Y, WIDTH, HEIGHT);
}
public int getBrickBottomY() {
return Y - HEIGHT;
}
}
Paddle.java
package com.seadnamcgillycuddy.unipong;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.Rectangle;
public class Paddle {
private static final int Y = 680;
private static final int WIDTH = 60;
private static final int HEIGHT = 10;
int x = 0;
int xa = 0;
private Game game;
public Paddle(Game game) {
this.game = game;
}
public void move () {
if (x + xa > 0 && x + xa < game.getWidth() - 60)
x = x + xa;
}
public void paint(Graphics2D g) {
g.fillRect(x, Y, WIDTH, HEIGHT);
}
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -game.speed;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = game.speed;
}
public Rectangle getBounds() {
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
public int getTopY() {
return Y - HEIGHT;
}
}
When you check for collisions with this line
return game.brick.getBounds().intersects(getBounds());
you're only checking intersection with one brick, brick, and not with the other 9 bricks you made, brick1, ..., brick9.
I'd recommend making an array of bricks, and then looping through them and checking collisions with each of them. Then, you can have as many bricks as you want and it won't take more code to check.

Categories

Resources