Игра Breakout Java - Застрял на печати кирпича на раме - PullRequest
0 голосов
/ 07 февраля 2020

В настоящее время я работаю над заданием, чтобы воссоздать упрощенную версию игры Breakout. Мне предоставили базу для кода, и я должен завершить приложение, однако я застрял на печати сами кирпичи на панели.

Проблемный раздел c находится в классе BreakoutPanel при использовании метода paintBricks (g) Я не уверен, как l oop пройти через сами кирпичи и затем вызвать метод paint (), который находится в другом учебный класс. Если я пытаюсь вызвать Brick.paint (g), он выдает мне сообщение «не могу сделать ссылку на статический c метод non-stati c». Я совершенно новичок в Java, поэтому любые советы или предложения будут оценены. Если вам нужен весь код, я тоже могу это предоставить.

import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class BreakoutPanel extends JPanel implements ActionListener, KeyListener {

    static final long serialVersionUID = 2L;

    private boolean gameRunning = true;
    private int livesLeft = 3;
    private String screenMessage = "";
    private Ball ball;
    private Paddle paddle;
    private Brick[] bricks;

    public BreakoutPanel(Breakout game) {

        addKeyListener(this);
        setFocusable(true);

        Timer timer = new Timer(5, this);
        timer.start();

        //Create a new ball object and assign it to the appropriate variable
        ball = new Ball();
        //Create a new paddle object and assign it to the appropriate variable
        paddle = new Paddle();
        //Create a new bricks array (Use Settings.TOTAL_BRICKS)
        bricks = new Brick[Settings.TOTAL_BRICKS];
        //Call the createBricks() method
        createBricks();
    }

    private void createBricks() {
        int counter = 0;
        int x_space = 0;
        int y_space = 0;
        for(int x = 0; x < 4; x++) {
            for(int y = 0; y < 5; y++) {
                bricks[counter] = new Brick((x * Settings.BRICK_WIDTH) + Settings.BRICK_HORI_PADDING + x_space, (y * Settings.BRICK_HEIGHT) + Settings.BRICK_VERT_PADDING + y_space);
                counter++;
                y_space++;
            }
            x_space++;
            y_space = 0;
        }
    }

    public void paintBricks(Graphics g) {       
        //Loop through the bricks and call the paint() method
        for (int i = 0; i < Settings.TOTAL_BRICKS; i++) {
            for (int j = 0; j < Settings.TOTAL_BRICKS; j++) {
                Brick.paint(g);
         }
        }
    }

    private void update() {
        if(gameRunning) {
            // Update the ball and paddle
            collisions();
            repaint();
        }
    }

    private void gameOver() {
        //Set screen message
        screenMessage = "Game Over";
        stopGame();
    }

    private void gameWon() {
        // Set screen message
        screenMessage = "Winner winner chicken dinner!";
        stopGame();
    }
    ;
    private void stopGame() {
        gameRunning = false;
    }

    private void collisions() {
        // Check for loss
        if(ball.y > 450) {
            // Game over
            livesLeft--;
            if(livesLeft <= 0) {
                gameOver();
                return;
            } else {
                ball.resetPosition();
                ball.setYVelocity(-1);
            }
        }

        // Check for win
        boolean bricksLeft = false;
        for(int i = 0; i < bricks.length; i++) {
            // Check if there are any bricks left
            if(!bricks[i].isBroken()) {
                // Brick was found, close loop
                bricksLeft = true;
                break;
            }
        }
        if(!bricksLeft) {
            gameWon();
            return;
        }

        // Check collisions
        if(ball.getRectangle().intersects(paddle.getRectangle())) {
            // Simplified touching of paddle
            // Proper game would change angle of ball depending on where it hit the paddle
            ball.setYVelocity(-1);
        }

        for(int i = 0; i < bricks.length; i++) {
            if (ball.getRectangle().intersects(bricks[i].getRectangle())) {
                int ballLeft = (int) ball.getRectangle().getMinX();
                int ballHeight = (int) ball.getRectangle().getHeight();
                int ballWidth = (int) ball.getRectangle().getWidth();
                int ballTop = (int) ball.getRectangle().getMinY();

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

                if (!bricks[i].isBroken()) {
                    if (bricks[i].getRectangle().contains(pointRight)) {
                        ball.setXVelocity(-1);
                    } else if (bricks[i].getRectangle().contains(pointLeft)) {
                        ball.setXVelocity(1);
                    }

                    if (bricks[i].getRectangle().contains(pointTop)) {
                        ball.setYVelocity(1);
                    } else if (bricks[i].getRectangle().contains(pointBottom)) {
                        ball.setYVelocity(-1);
                    }
                    bricks[i].setBroken(true);
                }
            }
        }
    }

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

        ball.paint(g);
        paddle.paint(g);
        paintBricks(g);

        // Draw lives left
        // TODO: Draw lives left in the top left hand corner



        // Draw screen message
        if(screenMessage != null) {
            g.setFont(new Font("Arial", Font.BOLD, 18));
            int messageWidth = g.getFontMetrics().stringWidth(screenMessage);
            g.drawString(screenMessage, (Settings.WINDOW_WIDTH / 2) - (messageWidth / 2), Settings.MESSAGE_POSITION);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        //Set the velocity of the paddle depending on whether the player is pressing left or right
        if(e.getKeyCode() == KeyEvent.VK_A) {
            paddle.setXVelocity(-2);
        } else if(e.getKeyCode() == KeyEvent.VK_D) {
            paddle.setXVelocity(2);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        //Set the velocity of the paddle after the player has released the keys
         if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_D) {
             paddle.setXVelocity(0);
         }            
    }

    @Override
    public void keyTyped(KeyEvent arg0) {

    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        update();
    }

}

Класс, из которого я пытаюсь вызвать метод рисования:


import java.awt.Graphics;

public class Brick extends Sprite {

    private boolean broken = false;

    public Brick(int x, int y) {
        //Set x using the parameter
        x = 0;
        //Set y using the parameter
        y = 0;
        //Set the width and height of the brick using Settings.BRICK_WIDTH/HEIGHT
        setWidth(Settings.BRICK_WIDTH);
        setHeight(Settings.BRICK_HEIGHT);
    }

    public boolean isBroken() {
        return broken;  //Return the correct variable
    }
    public void setBroken(boolean b) {
        //Set the broken variable using the parameter given
        b = true;
    }

    public void paint(Graphics g) {
        if(!broken) {
            g.fillRect(x, y, Settings.BRICK_WIDTH, Settings.BRICK_HEIGHT);
        }
    }
}

Я должен также упомянуть другие части кода не полностью завершены, и они не являются предметом моего вопроса, поэтому не стесняйтесь их игнорировать.

Ответы [ 2 ]

1 голос
/ 07 февраля 2020

Данное сообщение об ошибке требует, чтобы вы вызывали не-stati c метод не-stati c, то есть используя экземпляр класса. Попробуйте ниже код

    public void paintBricks(Graphics g) {       
            //Loop through the bricks and call the paint() method
            for (int i = 0; i < Settings.TOTAL_BRICKS; i++) {
                for (int j = 0; j < Settings.TOTAL_BRICKS; j++) {
                   // Brick.paint(g);
                     bricks[j].paint(g);                         
             }
            }
        }
1 голос
/ 07 февраля 2020

Появляется следующая ошибка, потому что вы пытаетесь вызвать функцию экземпляра, используя stati c reference, см. Различия между методами stati c и non-stati c в Java:

 "cannot make a static reference to the non-static method"

Поэтому используйте переменную private Brick[] bricks; в своей функции.
Измените свою функцию рисования, как показано ниже:

    public void paintBricks(Graphics g) {       
        //Loop through the bricks and call the paint() method
        for (Brick  brick:  bricks) {
                brick.paint(g);
        }
    }
...