0

This is our high school project where we modify a game source code. I want to ask on how to set the color of the panel into any color and what is the syntax?

Additionally, when I insert a loop in the main method, the panel opens infinitely even without finishing a game. Thus causing my computer to lag significantly. With this, I also wanted to include a loop on the game in order to restart even if the game ends(game over and restart).

THIS IS THE MAIN METHOD:

package BreakOuter;
public Breakout() {
    initUI();
}

public void initUI() {
    add(new c_Board());
    setTitle("Breakout");
    setBackground(Color.BLACK); 
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setResizable(false);
    pack();
}

public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
        var game = new Breakout();
        game.setVisible(true);

    });
}

This is the c_Board class(Still under construction)(The comments are for my group mates)

package BreakOuter;

//This is the Board class. Here we put the game logic.
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class c_Board extends JPanel {

    private Timer timer;
    private String message = "Game Over";
    private b_b_Ball ball;
    private b_b_Ball2 ball2;
    private b_c_Paddle paddle;
    private b_c_Paddle2 paddle2;
    private b_a_Brick[] bricks;
    private boolean inGame = true;

    public c_Board() {

        initBoard();
    }

    private void initBoard() {

        addKeyListener(new TAdapter());
        addKeyListener(new TAdapter2());
        setFocusable(true);
        setPreferredSize(new Dimension(a_Commons.WIDTH, a_Commons.HEIGHT));

        gameInit();
    }

    
 /**In the gameInit() method we create a ball, a paddle, and thirty bricks.
* Then we create and start a timer.*/   
    private void gameInit() {

        bricks = new b_a_Brick[a_Commons.N_OF_BRICKS];

        ball = new b_b_Ball();
        ball2 = new b_b_Ball2();
        paddle = new b_c_Paddle();
        paddle2 = new b_c_Paddle2();
        

        int k = 0;

        for (int i = 0; i < 5; i++) {

            for (int j = 0; j < 6; j++) {

                bricks[k] = new b_a_Brick(j * 50 + 100, i * 10 + 300); //j * >brick spaces + <indent to left, i * >vertical brick spaces + position of bricks downward
                k++;                                                 
            }
        }

        timer = new Timer(a_Commons.PERIOD, new GameCycle());
        timer.start();
    }
   //end
    
    

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        var g2d = (Graphics2D) g;

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);

 /**
Depending on the inGame variable, we either draw all the objects 
in the drawObjects() method or finish the game 
with the gameFinished() method.*/
 
        if (inGame) {

            drawObjects(g2d);
        } else {

            gameFinished(g2d);
        }
//end comment

        Toolkit.getDefaultToolkit().sync();
    }

    
/**The drawObjects() method draws all the objects of the game. 
 * The sprites are drawn with the drawImage() method.*/    
    
    private void drawObjects(Graphics2D g2d) {
        
        //draw ball 1
        g2d.drawImage(ball.getImage(), ball.getX(), ball.getY(),
                ball.getImageWidth(), ball.getImageHeight(), this);
        
        //draw ball 2
        g2d.drawImage(ball2.getImage(), ball2.getX(), ball2.getY(),
                ball2.getImageWidth(), ball2.getImageHeight(), this);
        
        //draw paddle1
        g2d.drawImage(paddle.getImage(), paddle.getX(), paddle.getY(),
                paddle.getImageWidth(), paddle.getImageHeight(), this);
        
        //draw paddle2
        g2d.drawImage(paddle2.getImage(), paddle2.getX(), paddle2.getY(),
                paddle2.getImageWidth(), paddle2.getImageHeight(), this);
        
        /**g2d.drawImage(paddle2.getImage(), paddle2.getX(), paddle2.getY(),
                paddle2.getImageWidth(), paddle2.getImageHeight(), this);*/
        
        

        for (int i = 0; i < a_Commons.N_OF_BRICKS; i++) {

            if (!bricks[i].isDestroyed()) {

                g2d.drawImage(bricks[i].getImage(), bricks[i].getX(),
                        bricks[i].getY(), bricks[i].getImageWidth(),
                        bricks[i].getImageHeight(), this);
            }
        }
    }
    
    
    
    
    
    
 /**The gameFinished() method draws "Game over" or "Victory" 
  * to the middle of the window.*/

    private void gameFinished(Graphics2D g2d) {

        var font = new Font("Verdana", Font.BOLD, 18);
        FontMetrics fontMetrics = this.getFontMetrics(font);

        g2d.setColor(Color.BLACK);
        g2d.setFont(font);
        g2d.drawString(message,
                (a_Commons.WIDTH - fontMetrics.stringWidth(message)) / 2,
                a_Commons.WIDTH / 2);
    }

    
    
 //controller of paddle1 
    private class TAdapter extends KeyAdapter {

        @Override
        public void keyReleased(KeyEvent e) {

            paddle.keyReleased(e);
        }

        @Override
        public void keyPressed(KeyEvent e) {

            paddle.keyPressed(e);
        }
    }

    
 //controller of paddle2
    private class TAdapter2 extends KeyAdapter {

        @Override
        public void keyReleased(KeyEvent e) {

            paddle2.keyReleased(e);
        }

        @Override
        public void keyPressed(KeyEvent e) {

            paddle2.keyPressed(e);
        }
    }
    
    
    
/**The timer periodically calls the actionPerformed() method, 
 * which calls the doGameCycle() method, creating a game cycle.*/
    
    private class GameCycle implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            doGameCycle();
        }
    }
//end of comment's scope
    
    
    
    
    
/**The doGameCycle() moves the ball and the paddle. 
 * We check for possible collisions and repaint the screen.*/
    
    private void doGameCycle() {

        ball.move(); //move the Player 1 Ball
        //ball2.move();//move the player 2 Ball
        paddle.move(); //move the Player 1 paddle
        paddle2.move(); //move the Player 2 paddle
        checkCollision(); //collision for player 1
        checkCollision2(); //collision for player 2
        repaint();// repaint method the game
    }//call all the methods to run a game cycle


    
    private void stopGame() {

        inGame = false;
        timer.stop();
    }
    
    
    
//If the ball hits the bottom, we stop the game.
    
   //Player 1 Collision Code
    private void checkCollision() {

        if (ball.getRect().getMaxY() > a_Commons.BOTTOM_EDGE){    //Lose Condition Player 1
            message = "Congratulations Player 2!";
            stopGame();}  
        
        if (ball.getRect().getMaxY() < a_Commons.TOP_EDGE){    //Win Condition Player 1
            message = "Congratulations Player 1!";
            stopGame();}  
        
       
            
/**We check how many bricks are destroyed. 
If we destroyed all N_OF_BRICKS bricks, we win the game.*/

        for (int i = 0, j = 0; i < a_Commons.N_OF_BRICKS; i++) {

            if (bricks[i].isDestroyed()) {

                j++;
            }

            if (j == a_Commons.N_OF_BRICKS) {

                message = "Congratulations Player 1!";
                stopGame();
            }
        }

        
        if ((ball.getRect()).intersects(paddle.getRect()) || (ball2.getRect()).intersects(paddle.getRect())) {

            int paddleLPos = (int) paddle.getRect().getMinX(); //paddle left x coordinate
            int paddleRPos = (int) paddle.getRect().getMaxX(); // paddle right x coordinate
            int ballLPos = (int) ball2.getRect().getMinX();
            int ballLPos2 = (int) ball.getRect().getMinX();

            int first = paddleLPos + ((paddleRPos - paddleLPos)/4) ;
            int second = paddleLPos +(paddleRPos - paddleLPos)/3 ;
            int third = paddleLPos +(paddleRPos - paddleLPos)/2 ;
            int fourth = paddleLPos +(paddleRPos - paddleLPos)/1 ;
            
/**If the ball hits the first part of the paddle, 
 * we change the direction of the ball to the north-west.*/

            if (ballLPos < first || ballLPos2 < first) {
                //hitting ball 1
                ball.setXDir(-1);
                ball.setYDir(-1);
                
                //hitting ball 2
                ball2.setXDir(-1);
                ball2.setYDir(-1);
            }
//end of comment's scope

            if (ballLPos >= first && ballLPos < second || ballLPos2 >= first && ballLPos2 < second ) {
                // hitting ball 1
                ball.setXDir(-1);
                ball.setYDir(-1 * ball.getYDir());
                
                //hitting ball 2
                ball2.setXDir(-1);
                ball2.setYDir(-1 * ball2.getYDir());
            }

            if (ballLPos >= second && ballLPos < third || ballLPos2 >= second && ballLPos2 < third ) {
                // hitting ball 1
                ball.setXDir(0);
                ball.setYDir(-1);
                
                // hitting ball 2
                ball2.setXDir(0);
                ball2.setYDir(-1);
            }  

            if (ballLPos >= third && ballLPos < fourth || ballLPos2 >= third && ballLPos2 < fourth ) {
                // hitting ball 1
                ball.setXDir(1);
                ball.setYDir(-1 * ball.getYDir());
                
                // hitting ball 2
                ball2.setXDir(1);
                ball2.setYDir(-1 * ball2.getYDir());
            }

            if (ballLPos > fourth) {
                //hitting ball 1
                ball.setXDir(1);
                ball.setYDir(-1);
                
                //hitting ball 2
                ball2.setXDir(1);
                ball2.setYDir(-1);
            }
        }

        for (int i = 0; i < a_Commons.N_OF_BRICKS; i++) {

            if ((ball.getRect()).intersects(bricks[i].getRect())) {

                int ballLeft = (int) ball.getRect().getMinX();
                int ballHeight = (int) ball.getRect().getHeight();
                int ballWidth = (int) ball.getRect().getWidth();
                int ballTop = (int) ball.getRect().getMinY();

                var pointRight = new Point(ballLeft + ballWidth + 1, ballTop);
                var pointLeft = new Point(ballLeft - 1, ballTop);
                var pointTop = new Point(ballLeft, ballTop - 1);
                var pointBottom = new Point(ballLeft, ballTop + ballHeight + 1);

                if (!bricks[i].isDestroyed()) {

                    if (bricks[i].getRect().contains(pointRight)) {

                        ball.setXDir(-1);
                    } else if (bricks[i].getRect().contains(pointLeft)) {

                        ball.setXDir(1);
                    }

 //If the ball hits the bottom of the brick, we change the y direction of the ball; it goes down.                   
                    if (bricks[i].getRect().contains(pointTop)) {

                        ball.setYDir(1);
                    } else if (bricks[i].getRect().contains(pointBottom)) {

                        ball.setYDir(-1);
                    }

                    bricks[i].setDestroyed(true);
                }
            }
        }
    } //Player 1 Collision of Paddle to Ball, Ball to Bricks
    
    
    
    
    
    
    
    
    
    //Player 2 Collision Code
    private void checkCollision2() {

        if (ball2.getRect().getMaxY() < a_Commons.TOP_EDGE){    //Lose Condition Player 2
            message = "Congratulations Player 1!";
            stopGame();}  
        
        if (ball2.getRect().getMaxY() > a_Commons.BOTTOM_EDGE){    //Win Condition Player 2
            message = "Congratulations Player 2!";
            stopGame();}                                          
        
        
    

        
/**We check how many bricks are destroyed. 
If we destroyed all N_OF_BRICKS bricks, we win the game.*/

        for (int i = 0, j = 0; i < a_Commons.N_OF_BRICKS; i++) {

            if (bricks[i].isDestroyed()) {

                j++;
            }

            if (j == a_Commons.N_OF_BRICKS) {

                message = "Congratulations Player 2!";
                stopGame();
            }
        }
        

        
        if ((ball2.getRect()).intersects(paddle2.getRect()) || (ball.getRect()).intersects(paddle2.getRect()) ) {

            int paddleLPos = (int) paddle2.getRect().getMinX();
            int paddleRPos = (int) paddle2.getRect().getMaxX();
            int ballLPos = (int) ball2.getRect().getMinX();
            int ballLPos2 = (int) ball.getRect().getMinX();

            int first = paddleLPos + ((paddleRPos - paddleLPos)/4) ;
            int second = paddleLPos +(paddleRPos - paddleLPos)/3 ;
            int third = paddleLPos +(paddleRPos - paddleLPos)/2 ;
            int fourth = paddleLPos +(paddleRPos - paddleLPos)/1 ;
            
/**If the ball hits the first part of the paddle, 
 * we change the direction of the ball to the north-west.*/

            if (ballLPos < first || ballLPos2 < first) {
                //hitting ball 2 by paddle 2
                ball2.setXDir(-1);
                ball2.setYDir(1);
                
                //hitting ball 1 by paddle 2
                ball.setXDir(-1);
                ball.setYDir(1);
            }
//end of comment's scope

            if (ballLPos >= first && ballLPos < second || ballLPos2 >= first && ballLPos2 < second ) {
                //hitting ball 2 by paddle 2
                ball2.setXDir(-1);
                ball2.setYDir(1 * ball.getYDir());
                
                //hitting ball 1 by paddle 2
                ball.setXDir(-1);
                ball.setYDir(1 * ball.getYDir());
                
                
            }

            if (ballLPos >= second && ballLPos < third || ballLPos2 >= second && ballLPos2 < third  ) {
                //hitting ball 2 by paddle 2
                ball2.setXDir(0);
                ball2.setYDir(1);
                
                //hitting ball 1 by paddle 2
                ball.setXDir(0);
                ball.setYDir(1);
            }

            if (ballLPos >= third && ballLPos < fourth || ballLPos2 >= third && ballLPos2 < fourth ) {
                //hitting ball 2 by paddle 2
                ball2.setXDir(1);
                ball2.setYDir(1 * ball2.getYDir());
                
                //hitting ball 1 by paddle 2
                ball2.setXDir(1);
                ball2.setYDir(1 * ball2.getYDir());
            }

            if (ballLPos > fourth) {
                //hitting ball 2 by paddle 2
                ball2.setXDir(1);
                ball2.setYDir(1);
                
                //hitting ball 1 by paddle 1
                ball2.setXDir(1);
                ball2.setYDir(1);
            }
        }

        for (int i = 0; i < a_Commons.N_OF_BRICKS; i++) {

            if ((ball2.getRect()).intersects(bricks[i].getRect())) {

                int ballLeft = (int) ball2.getRect().getMinX();
                int ballHeight = (int) ball2.getRect().getHeight();
                int ballWidth = (int) ball2.getRect().getWidth();
                int ballTop = (int) ball2.getRect().getMinY();

                var pointRight = new Point(ballLeft + ballWidth + 1, ballTop);
                var pointLeft = new Point(ballLeft - 1, ballTop);
                var pointTop = new Point(ballLeft, ballTop - 1);
                var pointBottom = new Point(ballLeft, ballTop + ballHeight + 1);

                if (!bricks[i].isDestroyed()) {

                    if (bricks[i].getRect().contains(pointRight)) {

                        ball2.setXDir(-1);
                    } else if (bricks[i].getRect().contains(pointLeft)) {

                        ball2.setXDir(1);
                    }

 //If the ball hits the bottom of the brick, we change the y direction of the ball; it goes down.                   
                    if (bricks[i].getRect().contains(pointTop)) {

                        ball2.setYDir(1);
                    } else if (bricks[i].getRect().contains(pointBottom)) {

                        ball2.setYDir(-1);
                    }

                    bricks[i].setDestroyed(true);
                }
            }
        }
    } //Player 2 Collision of Paddle to Ball, Ball to Bricks
}

enter image description here

enter image description here

R.E.F.
  • 37
  • 7
  • What is the c_Board class? Can you include that and any other code here. Also see that in the classes invoked here, the JPanel is not being set to have opaque property as false. See https://stackoverflow.com/questions/10148421/jpanel-setbackgroundcolor-black-does-nothing for more details on that. – Shivam Puri Apr 28 '22 at 19:18
  • "set the color of the panel" I am confused by this, as you are already calling setBackground. What exactly are you asking here? – ControlAltDel Apr 28 '22 at 19:38
  • "Additionally, when I insert a loop in the main method, the panel opens infinitely even without finishing a game. Thus causing my computer to lag significantly. " The lag is probably because you are doing busy waiting. Check out the Swing Timer - You can schedule game updates with this – ControlAltDel Apr 28 '22 at 19:39
  • Within the **c_Board** class in the `initBoard()` method, add these two lines of code: `setOpaque(true); setBackground(Color.BLACK);` – DevilsHnd - 退職した Apr 28 '22 at 20:20
  • A JPanel is opaque by default. – camickr Apr 29 '22 at 02:17

0 Answers0